为什么包含类的名称不被识别为返回值函数注释? [英] Why is the name of the containing class not recognized as a return value function annotation?

查看:29
本文介绍了为什么包含类的名称不被识别为返回值函数注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算使用 Python 函数注释来指定静态工厂方法的返回值的类型.我知道这是所需的用例之一 用于注释.

I was going to use Python function annotations to specify the type of the return value of a static factory method. I understand this is one of the desired use cases for annotations.

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

PEP 3107 指出:

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

Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

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

Trie is a valid expression in Python, isn't it? Python doesn't agree or rather, can't find the name:

def from_mapping(mapping) ->尝试:
NameError: name 'Trie' 未定义

值得注意的是,如果基本类型(例如 objectint)或标准库类型(例如 collections.deque) 被指定.

It's worth noting that this error does not happen if a fundamental type (such as object or int) or a standard library type (such as collections.deque) is specified.

是什么导致了这个错误,我该如何解决?

推荐答案

PEP 484 以 转发引用.

PEP 484 provides an official solution to this in the form of forward references.

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

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

以问题代码为例:

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

这篇关于为什么包含类的名称不被识别为返回值函数注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆