gpt4 book ai didi

python - 非泛型类型的不同运行时行为

转载 作者:行者123 更新时间:2023-12-03 23:39:20 25 4
gpt4 key购买 nike

考虑以下两种情况:

from queue import Queue
my_q: Queue[int] = Queue()
print(f"queue={my_q}")
from queue import Queue

class MyClass(object):
def __init__(self):
self.my_q: Queue[int] = Queue()

my_class = MyClass()
print(f"queue={my_class.my_q}")
运行前者(预期)会抛出 TypeError :
$ python3 run.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
my_q: Queue[int] = Queue()
TypeError: 'type' object is not subscriptable
然而后者没有,并且没有问题地继续打印语句:
$ python3 run.py
queue=<queue.Queue object at 0x7fb40265f730>
我希望 TypeError在这两种情况下。为什么没有 TypeErrorQueue[int]类型在类的 __init__ 内方法?

最佳答案

模块和类注释都可以在运行时访问,因此可以评估:

# example.py
a: int = 4
print(__annotations__) # {'a': <class 'int'>}
相反,函数的本地注释是不可访问的,因此永远不会被评估。

根据 PEP 3107 ,函数参数注释在运行时被评估并可用:

Once compiled, a function's annotations are available via the function's __annotations__ attribute.


根据 PEP 526 ,简单名称的模块和类级别注释在运行时被评估和可用。为了提高效率,函数内部的注释没有被明确地评估或存储:

In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the __annotations__ attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated 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.


PEP 563 / Python 3.10 ,不再立即评估注释。但是,模块、类和函数参数名称的注释仍然可能被延迟评估,因此应该是有效的表达式。函数的局部注释仍然无法访问,因此无法评估。

Note that as per PEP 526, local variable annotations are not evaluated at all since they are not accessible outside of the function's closure.

关于python - 非泛型类型的不同运行时行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66859447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com