函数内部未验证变量类型提示
Variable type hints are not validated inside function
当你执行这段代码时:
from typing import Dict
bar: Dict[int, int, int] = dict()
引发异常 TypeError
并显示一条消息 Too many parameters for typing.Dict; actual 3, expected 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 定义将 from __future__ import annotations
与 python 3.7+ 一起使用会阻止评估这些注释。
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
当你执行这段代码时:
from typing import Dict
bar: Dict[int, int, int] = dict()
引发异常 TypeError
并显示一条消息 Too many parameters for typing.Dict; actual 3, expected 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 定义将 from __future__ import annotations
与 python 3.7+ 一起使用会阻止评估这些注释。
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