我打算用Python function annotations来指定静态工厂方法返回值的类型.我知道这是注释的one of the desired use cases.

class Trie:
    @staticmethod
    def from_mapping(mapping) -> Trie:
        # docstrings and initialization ommitted
        trie = Trie()
        return trie

PEP 3107个国家表示:

函数注释只是在编译时将任意Python表达式与函数的各个部分关联起来的一种方式.

Trie在Python中是一个有效的表达式,不是吗?Python不同意,或者更确切地说,找不到名称:

def from_mapping(mapping) -> Trie:
NameError: name 'Trie' is not defined

值得注意的是,如果指定了基本类型(如objectint)或标准库类型(如collections.deque),则不会发生此错误.

What is causing this error and how can I fix it?

推荐答案

PEP 484以forward references的形式提供了这方面的正式解决方案.

当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,稍后解析.

对于问题代码:

class Trie:
    @staticmethod
    def from_mapping(mapping) -> Trie:
        # docstrings and initialization ommitted
        trie = Trie()
        return trie

变成:

class Trie:
    @staticmethod
    def from_mapping(mapping) -> 'Trie':
        # docstrings and initialization ommitted
        trie = Trie()
        return trie

Python-3.x相关问答推荐

Pandas 中每行的最大值范围

如何转换Pandas中的数据,以使我 Select 的列名变为行值并增加行?

如何在M x N数组的行中找到所有值的组合

为什么我在BLE中的广告代码在发送包裹之间需要大约1秒

新行是pandas数据帧中旧行的组合

为什么我无法在django中按月筛选事件?

pip install saxonche v 12.1.0 产生 FileNotFoundError

切片的Python复杂性与元组的星号相结合

Python defaultdict 在获取时返回 None,尽管使用默认值初始化

为什么 f-strings 比 str() 更快地解析值?

从 Python2 到 Python3 的这种解包行为的变化是什么?

保存 StandardScaler() 模型以用于新数据集

Python 3.5 中编码 utf-8 和 utf8 的区别

Python 3 与 Python 2 映射行为

如何将二进制(字符串)转换为浮点值?

Python3 - 如何从现有抽象类定义抽象子类?

使用完整路径激活 conda 环境

命名参数可以与 Python 枚举一起使用吗?

带有数千个逗号刻度标签的 MatPlotLib 美元符号

将 Python SIGINT 重置为默认信号处理程序