【问题标题】:from __future__ import annotations从 __future__ 导入注释
【发布时间】:2020-05-01 14:53:44
【问题描述】:

Python doc __future__

在关于__future__ 的python 文档中,下面有一个表格,其中显示 注释“可选”3.7.0b1 和“强制”4.0 但是我仍然可以在 3.8.2 中使用注释而不导入注释,那么它有什么用。

>>> def add_int(a:int, b:int) -> int:
...     return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

我怀疑我没有清楚地理解这里“可选”和“强制”的含义

【问题讨论】:

    标签: python python-3.x annotations


    【解决方案1】:

    强制是一个有趣的词选择。我想这意味着它是默认的语言。您不必使用 from __future__ import annotations 启用它

    annotations 功能指的是 PEP 563:推迟对注释的评估。它是对现有 annotations feature 的增强,最初在 python 3.0 中引入并在 python 3.5 中重新定义为 type hints,这就是您的代码在 python 3.8 下工作的原因。

    以下是 python 3.7+ 中可选的 from __future__ import annotations 更改:

    class A:
        def f(self) -> A: # NameError: name 'A' is not defined
            pass
    

    但是这行得通

    from __future__ import annotations
    
    class A:
        def f(self) -> A:
            pass
    

    请参阅 python 3.7 中的this 章节关于延迟注释的新功能:

    由于此更改破坏了兼容性,因此需要在 Python 3.7 中使用 __future__ 导入为每个模块启用新行为:

    from __future__ import annotations

    它将成为 Python 3.10* 中的默认设置。

    * 它在 3.10(python3.7 发布时)宣布为默认值,但现在已移至更高版本

    【讨论】:

    • 它没有完全回答我的问题“可选”以及为什么我的代码在没有从 future 导入注释的情况下工作
    • bc 函数 __ 注释 __ (dunder) 是在 Python 3.0 中根据 PEP 3107 引入的。(参见 bit.ly/python-annotations)。随后的 PEP 添加了类型提示 (3.5),更新了语法 (3.6),更改了评估时间 (3.7),并将注释语义限制为类型提示 (3.8)。 HTH。
    • from __future__ import annotations 在 Python 3.10 中将不是默认值,但在后续版本中:dev.to/tiangolo/…(请参阅“下一步”部分)。
    【解决方案2】:

    默认情况下是强制性的。 可选,因为需要从from __future__ import annotations 语句“激活”

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 2019-07-26
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      相关资源
      最近更新 更多