【问题标题】:mypy possible cyclic definition: TypedDict Class Attribute is Parent Class Referencemypy 可能的循环定义:TypedDict 类属性是父类引用
【发布时间】:2021-09-02 02:58:47
【问题描述】:

我正在使用 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

【问题讨论】:

  • 参见github.com/python/mypy/issues/731#issuecomment-752157487,这是因为HackerNewsComment 作为TypedDict 在运行时被擦除为dictprint(type(HackerNewsComment(kids=[])) 将打印 <class 'dict'>。要递归使用HackerNewsComment,您可以将其设为@dataclass。然后执行HackerNewsComment(**api_response),其中api_response 是Hacker News API 返回的dict
  • 谢谢你,如果你想写这个作为答案,我会接受的。

标签: python mypy python-typing


【解决方案1】:

参见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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 2020-06-10
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2016-11-15
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多