python - mypy 抱怨 attrs 类中的 TypedDict 具有不兼容的类型
问题描述
我DictWithOnlyX
在 attrs 数据类中有一个 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")
具有讽刺意味的是,当通过声明的类型来解决 mypy 问题时,attrib()
我得到了另一个 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")
上述代码的两个版本都运行良好。蟒蛇 3.7.5。
两条错误消息都很神秘,因为它们看起来自相矛盾——(据报道)相同的类型怎么可能是“不兼容的”?
解决方案
对我来说,这看起来像是一个 mypy 错误。但令我惊讶的是它的效果如此之好,因为您完全避开了 attrs 的打字支持!定义类的惯用方式是
@attrs(auto_attribs=True)
class Example(object):
name: str = ""
dx: DictWithOnlyX = Factory(DictWithOnlyX)
但这会导致相同的错误消息。
推荐阅读
- python - 删除熊猫时间序列中的重复项
- powershell - PowerShell 调用 advapi32.dll GetEffectiveRightsFromAclA 崩溃 PowerShell
- r - 为什么 SPARQL 查询在 R 包中比在 Land Registry 中的查询时间长 30 倍?
- count - 将 setInterval 计数重置为零
- python - 模拟鼠标按下窗口(有效,但位置不起作用)
- vue.js - 从父级到子级的动态道具绑定
- google-drive-api - NSSM - 试图访问 Software/Google/DriveFS/Share
- javascript - 如何不呈现 ViewChild 元素,而是在父组件中访问它?
- linux - 如何使用自定义 bash 文件(不是来自 .bachrc 或配置文件或其他 shell)初始化/设置 shell?
- babeljs - 删除 @babel/plugin-proposal-class-properties 时出现错误“当前未启用对实验语法 'classProperties' 的支持”