![](/img/trans.png)
[英]How to add type hints for an inner or nested function inside the stub file
[英]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
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 - 变量注释的语法#Runtime Effects of Type Annotations 中定义。
注释局部变量将导致解释器将其视为局部变量,即使它从未被赋值。 不会评估局部变量的注释:
def f(): x: NonexistentName # No error.
但是,如果它是在模块或类级别,则类型将被评估:
x: NonexistentName # Error! class X: var: NonexistentName # Error!
此外, PEP 563 -- Postponed Evaluation of Annotations定义了将from __future__ import annotations
与 python 3.7+ 一起使用可防止对这些注释进行评估。
此 PEP 建议更改函数注释和变量注释,以便不再在函数定义时评估它们。 相反,它们以字符串形式保存在 __annotations__ 中。
from __future__ import annotations
from typing import Dict
bar: Dict[int, int, int] = dict() # no errors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.