myy可能的循环定义:TypedDict类属性是父类引用



我正在使用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 version: 0.910
  • python版本:3.8.5
  • OS: WSL on Windows

查看此GitHub问题"支持递归类型",这是因为HackerNewsComment作为TypedDict在运行时被擦除为dictprint(type(HackerNewsComment(kids=[]))将打印<class 'dict'>。要递归地使用HackerNewsComment,可以将其设置为@dataclass。然后执行HackerNewsComment(**api_response),其中api_response是从Hacker News API返回的dict

最新更新