return 类型提示的范围 Python

Scope of return type hints in Python

我有两个 类,A 和 B,它们都有 return 另一个实例的方法。当我不使用类型提示时,这种情况很好,但是,我无法合并类型提示,如下例所示:

class A:
    def return_B_with_out_annotation(self):
        return B()
    
    def return_B_with_annotation(self) -> B():
        return B()


class B:
    pass

执行上述代码(在 Python 3.8 中)会产生以下错误:

NameError: name 'B' is not defined

所以我的问题是,为什么方法 A.return_B_with_out_annotation 是有效代码,而 A.return_B_with_annotation 不是?

对于Python 3.7+

您需要添加以下导入以允许您对 类 尚未定义

使用类型提示
from __future__ import annotations

PEP 563 is where this behaviour is proposed

发生这种情况是因为 A class 中的方法 return_B_with_annotation 尚未意识到 class B 在其范围之外。 有两种方法可以解决这个问题。 一种是在 A 之前先创建 Class B,如下所示

class B:
    pass
class A:
    def return_B_with_out_annotation(self):
        return B()
    
    def return_B_with_annotation(self) -> B():
        return B()

否则你应该将注释从 future 模块导入到 python 作为

from future import annotations

您的代码将是

from __future__ import annotations

class A:
def return_B_with_out_annotation(self):
    return B()

def return_B_with_annotation(self) -> B():
    return B()


class B:
pass

^这个比较推荐