当您执行此代码时:
from typing import Dict
bar: Dict[int, int, int] = dict()
异常TypeError
,并带有消息Too muchparametersfortyping.Dict;实际为 3,预期为 2
。但是当您在函数内定义变量时:
from typing import Dict
def foo():
bar: Dict[int, int, int] = dict()
foo()
这次没有引发异常。这是预期行为还是错误?
最佳答案
这是预期行为,定义于 PEP 526 -- Syntax for Variable Annotations #Runtime Effects of Type Annotations .
Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to. Annotations for local variables will not be evaluated:
def f(): x: NonexistentName # No error.
However, if it is at a module or class level, then the type will be evaluated:
x: NonexistentName # Error! class X: var: NonexistentName # Error!
此外,PEP 563 -- Postponed Evaluation of Annotations定义在 python 3.7+ 中使用 from __future__ import 注解
会阻止对这些注解进行求值。
This PEP proposes changing function annotations and variable annotations so that they are no longer evaluated at function definition time. Instead, they are preserved in __annotations__ in string form.
from __future__ import annotations
from typing import Dict
bar: Dict[int, int, int] = dict() # no errors
关于python - 变量类型提示在函数内部未验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69675872/