Jey*_*mon 2 python type-hinting
当你执行这段代码时:
from typing import Dict
bar: Dict[int, int, int] = dict()
Run Code Online (Sandbox Code Playgroud)
引发TypeError带有消息的异常。Too many parameters for typing.Dict; actual 3, expected 2但是当您在函数内定义变量时:
from typing import Dict
def foo():
bar: Dict[int, int, int] = dict()
foo()
Run Code Online (Sandbox Code Playgroud)
这次没有例外。这是预期行为还是错误?
这是预期行为,并在PEP 526 - 变量注释语法#Runtime Effects of Type Annotations中定义。
注释局部变量将导致解释器将其视为局部变量,即使它从未被分配。局部变量的注释将不会被评估:
Run Code Online (Sandbox Code Playgroud)def f(): x: NonexistentName # No error.但是,如果它是在模块或类级别,则将评估类型:
Run Code Online (Sandbox Code Playgroud)x: NonexistentName # Error! class X: var: NonexistentName # Error!
此外,PEP 563 - 推迟评估注释定义from __future__ import annotations与 python 3.7+ 一起使用可防止评估这些注释。
此 PEP 建议更改函数注释和变量注释,以便不再在函数定义时评估它们。相反,它们以字符串形式保存在 __annotations__ 中。
x: NonexistentName # Error!
class X:
var: NonexistentName # Error!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
271 次 |
| 最近记录: |