[英]In Python, how to get typing right when using a class decorator?
這是我第一次嘗試制作 Python 裝飾器,我謙虛地承認在這樣做時從許多 StackOverflow 帖子中汲取了靈感。 當我清理__instancecheck__
方法時,最后兩個斷言停止觸發,但現在 PyCharm 的內置__instancecheck__
對最后一個斷言不滿意。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.