在attrs数据类Example
中有一个TypedDictDictWithOnlyX
,其中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错误-猛击鼹鼠!你知道吗
@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的输入!定义类的惯用方法是
但这会导致相同的错误消息。你知道吗
相关问题 更多 >
编程相关推荐