变量类型提示在函数内部未验证

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)

这次没有例外。这是预期行为还是错误?

umi*_*itu 5

这是预期行为,并在PEP 526 - 变量注释语法#Runtime Effects of Type Annotations中定义。

注释局部变量将导致解释器将其视为局部变量,即使它从未被分配。局部变量的注释将不会被评估:

def f():
    x: NonexistentName  # No error.
Run Code Online (Sandbox Code Playgroud)

但是,如果它是在模块或类级别,则将评估类型:

x: NonexistentName  # Error!
class X:
    var: NonexistentName  # Error!
Run Code Online (Sandbox Code Playgroud)

此外,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)