我在attrs数据类DictWithOnlyX
中有一个TypedDict Example
,尽管声明了返回类型,但mypy抱怨从我的类的getdict()
方法返回的类型:
from typing_extensions import TypedDict
from attr import attrs, attrib, Factory, fields
DictWithOnlyX = TypedDict('DictWithOnlyX', {"x": str})
@attrs
class Example(object):
name: str = attrib(default="")
dx = attrib(factory=DictWithOnlyX)
def getdict(self) -> DictWithOnlyX:
return self.dx # <-- mypy compains
mypy抱怨error: Incompatible return value type (got "DictWithOnlyX", expected "DictWithOnlyX")
具有讽刺意味的是,当通过声明attrib()
的类型解决mypy问题时,我又遇到了另一个mypy错误-hack鼠!
@attrs
class Example(object):
name: str = attrib(default="")
dx: DictWithOnlyX = attrib(factory=DictWithOnlyX) # <-- mypy compains
def getdict(self) -> DictWithOnlyX:
return self.dx
mypy抱怨error: Incompatible types in assignment (expression has type "DictWithOnlyX", variable has type "DictWithOnlyX")
上述代码的两个版本运行确定。 Python 3.7.5。
这两种错误消息都是神秘的,因为它们似乎是自相矛盾的-(报告为)相同的类型怎么能'不兼容'?
对我来说,这看起来像是个臭虫。但令我惊讶的是,它的效果很好,因为您完全避开了attrs的键入支持!定义类的惯用方式是
@attrs(auto_attribs=True)
class Example(object):
name: str = ""
dx: DictWithOnlyX = Factory(DictWithOnlyX)
但是会导致相同的错误消息。