到处使用“from __future__ import 注解”有什么缺点吗?

mar*_*lli 17 python annotations python-typing

PEP 563来看,似乎应该有轻微的性能提升,因为它解决了

类型提示在模块导入时执行,这在计算上不是免费的。

那么...我是否可以/应该将其包含from __future__ import annotations在包中的每个文件中,或者是否有任何原因应将其从某些文件中排除?

Mis*_*agi 12

TLDR:有些东西不适用于from __future__ import annotations. 由于 Python 的未来版本将强制推迟评估,因此争取向前兼容性的代码首先不应依赖于即时评估。

\n
\n

由于from __future__ import annotations避免了类型提示的求值,因此任何依赖于求值类型提示的内容都必须显式求值类型提示。这在顶级模块或类范围之外通常是不可能的,除非locals明确处理。

\n

例如,functools.singledispatch如果注释评估被推迟,则不能在函数内使用类型提示:

\n
from __future__ import annotations\nfrom typing import Type\nfrom functools import singledispatch\n\ndef non_global_sdp(local_type: Type):\n    @singledispatch\n    def default(arg): print("default")\n\n    @default.register\n    def case_a(arg: local_type): print("case_a")\n\n    return default\n\ncases = non_global_sdp(int)  # NameError: name \'local_type\' is not defined\n
Run Code Online (Sandbox Code Playgroud)\n
\n

推迟评估注释和强制引入版本的确切语义尚未确定。当前提案中的特征from __future__ import annotations是最具限制性的;任何必须与未来版本的 Python 一起使用的代码都应该使用from __future__ import annotations以避免对提示计算的隐藏依赖。

\n
\n

__future__\xe2\x80\x94 Future 语句定义 (Python 3.11)

\n

[1]from __future__ import annotations之前计划在 Python 3.10 中强制执行,但 Python 指导委员会两次决定推迟更改(Python 3.10 的公告Python 3.11 的公告)。尚未做出最终决定。另请参见 PEP 563 和 PEP 649。

\n
\n

  • 您的答案不清楚“from __future__ import comments”是好还是坏。这是一个很好的默认值,对吧?“争取向前兼容性的代码首先不应依赖于即时评估”在实践中意味着什么? (2认同)
  • @MarcosPereira“……是好是坏。” 这不是问题,而且“复杂得多”。““……”在实践中意味着什么?这意味着答案末尾所说的:“任何必须与未来版本的 Python 一起使用的代码都应该使用 `from __future__ import 注解`以避免对提示求值的隐藏依赖。”。 (2认同)