我有None
或dict
的班级成员.
class A:
def __init__(self, a: bool = False) -> None:
self.has_a = a
self.prop_a = {"a" : 1} if a else None
def length_prop(self) -> int:
length_prop = None
if self.has_a:
length_prop = len(self.prop_a)
return length_prop
如果我用mypy
判断打字:
test.py:10: error: Argument 1 to "len" has incompatible type "Optional[Dict[str, int]]"; expected "Sized"
length_prop = len(self.prop_a)
^
test.py:11: error: Incompatible return value type (got "Optional[int]", expected "int")
return length_prop
很容易理解,因为它不知道self.prop_a
是否真的是dict
.