python-3.x - 在 Python 中,如何在使用类装饰器时正确输入?
问题描述
这是我第一次尝试制作 Python 装饰器,我谦虚地承认在此过程中从许多 StackOverflow 帖子中汲取了灵感。当我清除该__instancecheck__
方法时,最后两个断言停止触发,但现在 PyCharm 的内置 linter 对最后一个断言不满意。
Expected type 'Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]', got 'Multiton' instead.
打字问题的根源是什么,如何解决?
此外,在做出__init__
评论者推荐的更改后,另一个警告浮出水面。
Local variable 'instance' might be referenced before assignment.
class Multiton(object):
""" When init parameters match, reuse an old initialized object instead of making a new one. """
def __init__(self, cls):
# self.__dict__.update({'instances': list(), 'cls': cls})
self.instances = list()
self.cls = cls
def __call__(self, *args, **kwargs):
# make a key with the parameters
key = (args, kwargs)
# search for a matching old instance
found = False
for instance in self.instances:
if instance['key'] == key:
found = True
break
# if not found then create a new instance
if not found:
instance = {'key': key, 'object': self.cls(*args, **kwargs)}
self.instances.append(instance)
return instance['object']
def __instancecheck__(self, other):
return isinstance(other, self.cls)
@Multiton
class YourClass:
def __init__(self, number):
self.number = number
yc_1 = YourClass(1)
yc_2 = YourClass(2)
yc_two = YourClass(2)
assert yc_1 != yc_2
assert yc_2 == yc_two
assert not isinstance(yc_1, Multiton)
assert isinstance(yc_1, YourClass)
解决方案
错误警告是 PyCharm 错误,希望 JetBrains 的优秀人员能尽快修复。
https://youtrack.jetbrains.com/issue/PY-38590 https://youtrack.jetbrains.com/issue/PY-49966
推荐阅读
- apache-spark - 将 Power BI 连接到 Spark thrift
- c# - Update void doesnt work for me, what am I missing?
- node.js - 将 gsap 节点模块与 Meteor 一起使用
- mysql - sql连接来自同一个表的值
- android - Save a text file from a Flutter Android app that can be accessed by user
- reactjs - 列表数据更改时,材质 UI 列表滚动不会重置
- python - Kivy Buildozer VM - Can't build apk - Build failed: python-for-android
- node.js - 在 cloudinary 依赖 npm install 之后找不到模块“cloudinary”的声明文件
- r - 如何在 ggplot2 qplot() 和 geom_() 中自动完成?
- .net - Entity framework throws NullReferenceException