【问题标题】:Variable type hints are not validated inside function变量类型提示未在函数内部验证
【发布时间】:2021-12-09 00:55:55
【问题描述】:

当你执行这段代码时:

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()

这次没有引发异常。这是预期的行为还是错误?

【问题讨论】:

    标签: python type-hinting


    【解决方案1】:

    这是预期行为,在PEP 526 -- Syntax for Variable Annotations #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 定义在 python 3.7+ 中使用 from __future__ import annotations 会阻止对这些注释进行评估。

    此 PEP 建议更改函数注释和变量注释,以便在函数定义时不再评估它们。相反,它们以字符串形式保存在 __annotations__ 中。

    from __future__ import annotations
    from typing import Dict
    
    bar: Dict[int, int, int] = dict()  # no errors
    

    【讨论】:

    • 至于 为什么 本地注解不被评估,请记住注解本身可以是任意代码,而不仅仅是类型提示(尽管不推荐使用非类型提示)。因此,当函数内没有其他代码被评估时,评估函数定义中的注释将是一个例外。 PEP 563 通过指定将在定义或调用时评估 no 注释来使其成为一个有争议的问题:注释成为隐含的​​ str 文字,只有在您明确这样做时才会被评估。跨度>
    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2016-12-02
    • 2013-09-28
    • 2010-12-21
    相关资源
    最近更新 更多