我用MyPy做我的类型检查器,我遇到了这种奇怪的行为。我希望有人能给我提供一份能解释为什么会发生这种情况的参考资料(一份变通方案也不错)
以下代码使用MyPy引发0个错误:
class HackerNewsComment:
# ...
kids: List["HackerNewsComment"] # A list of child comments under this one
作为参考,这也会引发0个错误
class HackerNewsComment(object): # Even putting `Generic[T]` is ok according to mypy.
# ...
kids: List["HackerNewsComment"] # A list of child comments under this one
但突然间:
class HackerNewsComment(TypedDict):
# ...
kids: List["HackerNewsComment"] # A list of child comments under this one
Mypy接着说:Cannot resolve name "HackerNewsComment" (possible cyclic definition)
在TypedDict
类中是什么导致mypy恐慌?
可能的相关信息:
参见this GitHub issue "Support recursive types",这是因为
HackerNewsComment
作为TypedDict
在运行时被擦除为dict
print(type(HackerNewsComment(kids=[]))
将打印<class 'dict'>
。要递归地使用HackerNewsComment
,可以将其设为@dataclass
。然后执行HackerNewsComment(**api_response)
,其中api_response
是从Hacker News API返回的dict
相关问题 更多 >
编程相关推荐