gpt4 book ai didi

python - 从 __future__ 导入注释

转载 作者:行者123 更新时间:2023-12-04 11:07:30 28 4
gpt4 key购买 nike

Python doc __future__
在 python 文档中关于 __future__下表显示了
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'>}
我怀疑我不清楚这里“可选输入”和“强制输入”的含义

最佳答案

强制是一个有趣的词选择。我想这意味着它在语言中是默认的。您不必使用 from __future__ import annotations 启用它annotations功能是指 PEP 563:延期 注释的评估。它是对现有 annotations feature 的增强它最初在 python 3.0 中引入并重新定义为 type hints在 python 3.5 中,这就是为什么你的代码在 python 3.8 下工作的原因。
这是可选的 from __future__ import annotations python 3.7+的变化:

class A:
def f(self) -> A: # NameError: name 'A' is not defined
pass
但这有效
from __future__ import annotations

class A:
def f(self) -> A:
pass
this python 3.7 中关于延迟注释的新内容:

Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a __future__ import:

from __future__ import annotations

It will become the default in Python 3.10.

关于python - 从 __future__ 导入注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544854/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com