我们可以在 Python 中注释变量,同时避免注释的运行时类型擦除吗?

Can we annotate a variable in Python while avoiding runtime type erasure of annotation?

我一直在阅读这个主题,我的理解是,如果我们注释一个参数,Python 不会在运行时删除注释。所以在这个例子中:

def f(x:int):
    return x

x 是整数的事实在运行时仍然保留。 相比之下,如果我们有:

def f():
    y :int ; y=5 
    return y

y :int不保留。无论如何在 Python 中为赋值语句声明类型,以便在运行时保留注释?

编辑:

我的意思是:

class A:
    def f(self,x:int):
        y :int ; y=5
        return (x,y)

print(typing.get_type_hints(A.f))

结果是:

{'x': <class 'int'>}

所以我们只能恢复参数类型但y:int已被删除

无法在运行时获取函数局部注释。这已编码在初始 PEP 中,此后未被撤销。

PEP 562 – Syntax for Variable AnnotationsRuntime

Effects of Type Annotations

Also the value of having annotations available locally does not offset the cost of having to create and populate the annotations dictionary on every function call. Therefore, annotations at function level are not evaluated and not stored.


潜在的问题是函数局部注释可以依赖于函数局部状态:

def f(y_type):
    y: y_type = y_type() 
    return y

这使得“f 的函数局部注释”未定义——只有特定调用 f(y_type) 具有明确定义的注释。因此,每次调用都必须重新创建注释——这对每次调用来说都是一项昂贵的开销,并且仍然不会在函数对象本身上公开注释。
由于拥有函数局部注释的成本被认为不值得,因此它们在运行时被丢弃。