当我在以下代码上运行 mypy 时,我看到几个错误:
from typing import Callable, Type
def class_creator(outside_reference: Callable[[str], None]) -> Type[object]:
class SomeClass():
reference: Callable[[str], None]
def __init__(self) -> None:
self.reference = outside_reference
super().__init__()
def __str__(self):
self.reference("SomeClass instance")
return SomeClass
def callback(string: str) -> None:
print("Prepping: " + string)
instance = class_creator(callback)()
print(instance)
以下是错误:
test.py:9: error: Cannot assign to a method
test.py:9: error: Invalid self argument "SomeClass" to attribute function "reference" with type "Callable[[str], None]"
test.py:9: error: Incompatible types in assignment (expression has type "Callable[[str], None]", variable has type "Callable[[], None]")
第 9 行是
self.reference = outside_reference
。我基本上肯定我只是误解了一些东西,但我看不出我哪里出错了。
这是最小的可重复引用。如果我将类型从
Callable[[str], None]
更改为 int
(并且实际上不调用它),那么它运行得很好而不会显示任何错误。只有当我切换到 Callable
时,它才开始显示这些错误。我的注释应该在这里做什么?
最佳答案
在 https://github.com/python/mypy/issues/708 中的问题得到修复之前,解决此问题的一种干净方法是将 callable 属性设为可选,并将其包装在带有断言的方法中:
from typing import Any, Callable, Optional
class SomeClass:
_reference: Optional[Callable[[], Any]]
def reference(self) -> Any:
assert self._reference is not None
return self._reference()
def __init__(self, reference):
self.reference = reference
c = SomeClass(lambda: 42)
print(c.reference())
$ mypy test.py
Success: no issues found in 1 source file
关于python - 对 Callable 的 mypy 类型检查认为成员变量是一个方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51811024/