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

2024-05-15 17:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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恐慌?

可能的相关信息:

  • mypy版本:0.910
  • python版本:3.8.5
  • 操作系统:Windows上的WSL

Tags: ofchild错误thisonecommentslistclass
1条回答
网友
1楼 · 发布于 2024-05-15 17:56:07

参见this GitHub issue "Support recursive types",这是因为HackerNewsComment作为TypedDict在运行时被擦除为dictprint(type(HackerNewsComment(kids=[]))将打印<class 'dict'>。要递归地使用HackerNewsComment,可以将其设为@dataclass。然后执行HackerNewsComment(**api_response),其中api_response是从Hacker News API返回的dict

相关问题 更多 >