mypy可能的循环定义:TypedDict Class Attribute is Parent Class Reference
mypy possible cyclic definition: TypedDict Class Attribute is Parent Class Reference
我正在使用 MyPy 作为我的类型检查器,并且我 运行 进入了这个 st运行ge 行为。我希望有人能给我指出一个参考资料来解释为什么会发生这种情况(解决方法也很好)。
以下代码在 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
class 中的什么导致 mypy 崩溃?
可能的相关信息:
- mypy 版本:0.910
- python版本:3.8.5
- OS:WSL Windows
请参阅 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
我正在使用 MyPy 作为我的类型检查器,并且我 运行 进入了这个 st运行ge 行为。我希望有人能给我指出一个参考资料来解释为什么会发生这种情况(解决方法也很好)。
以下代码在 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
class 中的什么导致 mypy 崩溃?
可能的相关信息:
- mypy 版本:0.910
- python版本:3.8.5
- OS:WSL Windows
请参阅 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