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

标签 python type-hinting

当您执行此代码时:

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/

相关文章:

返回多个返回值的函数的 Python 类型提示

python - 如何动态使用Python的类型提示来指示返回值与参数类型相同

python3 输入 : extract argument list from Callable

python - 无法找到使用请求从网页中获取零件号的正确方法

python - 使用 Python 连接 ElephantSQL

python - 使用 pyparsing 累积

python - 如何正确使用python类型提示?

python - 如何在 Python 中为类型定义别名以进行类型提示

python - 如何为标签列表创建 "scrollbar"? python tkinter

python - Python Opencv2 +网络摄像头面部检测,未检测到面部,无错误