Python类型提示:自引用类型检查

ogq8wdun  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(230)

考虑到我通常使用,语言,我认为静态类型确实会让我在Python中的生活变得更轻松。我创建了这样一个类:

class node(object):
    """
    properties, constructor, etc.
    """

    def add_outneighbor(self, neighbor: node) -> None:
        """
        do stuff
        """

Flake8告诉我nodeadd_outneighbor的定义中是一个未知类型。目前我正在解决isinstance(arg, type)的问题,但这似乎违背了类型提示的目的。有没有更好的方法来做到这一点?This是我为了获得类型提示的信息而引用的资源。但我找不到任何关于自我参照的讨论。

nzk0hqpo

nzk0hqpo1#

解释器告诉您node是未知类型的原因是,除非您使用Python 4,否则在注解中使用它之前必须定义node
我建议插入以下声明:from __future__ import annotations,它会自动将注解存储为字符串。

igsr9ssn

igsr9ssn2#

特殊的Self类型注解是在python3.11中引入的。
文档中的使用示例:

from typing import Self

class Foo:
   def return_self(self) -> Self:
      return self

使用原始问题的示例:

from typing import Self

class node(object):
    """
    properties, constructor, etc.
    """

    def add_outneighbor(self, neighbor: Self) -> None:
        """
        do stuff
        """
        pass

相关问题