__future__ 语句如何知道新 python 版本的语法?

How does __future__ statements know the syntax of new python versions?

我已经解决了有关 future 模块如何工作的问题。

What is __future__ in Python used for and how/when to use it, and how it works

.

但我仍然不明白的是,今天创建的解释器如何知道未来版本中代码的语法。

我的想法是,当他们为 2.7 版本创建一个 python 解释器时,他们构建代码并创建一个可执行文件,不要触摸或修改它,用户将下载它并用它。假设 python 2.7 可执行文件是在 2009 年创建的。

python 3.7可执行文件是在2017中创建的,python如何2.7导入print_function时知道要编译什么代码? python 2.7解释器如何知道print_function的代码是什么,将在创建解释器后引入。

我的看法是正确的还是完全错误的?

谁能解开这个谜团。

from __future__ import ... 只是一种过于可爱的说法,表示某项功能现在可用 ,但您必须选择加入。将来,它将成为默认功能或必需。

每个定义的导入都带有两条信息:使该功能可选可用的版本,以及该功能将成为的版本强制性__future__ 模块中删除 任何功能。

从 Python 3.8 开始,__future__ 中有九个功能可用。除了一个 annotations 之外,其他都是强制性的。在旧版本 Python 中永远不需要 运行 的新代码不需要导入它们。使用它们的旧代码不需要更新,即使导入实际上是空操作。在 Python 4.0 发布之前,annotations 仍将是可选功能;没有日期,但保证 annotations 将成为该版本的一部分,并且 不是 任何早期版本的强制性部分。

Python 2.7.0 在 Python 3.0.0 之后发布,即在 print 变成函数之后。通过传递通过 __future__ 导入激活(识别)的选项,编译器可以使用这种语法更改。

编译器确实实现了这样的新语法;只有激活是可选的。这意味着您确实需要下载更新版本的 Python 才能选择加入其中一项 __future__ 功能。 Python 2.7.0 was released in 2010 while Python 3.0.0 was released in 2008. So from the 2.7 point of view it was actual an "old" feature. Even though Python 2.5.6 was released three years after 3.0.0 it doesn't contain the opt-in for the print function since it was not implemented in that minor version of Python (2.5.0 which was released in 2006). The term "future" here refers to future (minor) versions of Python where a feature will become mandatory. But the plans (the PEP) for that feature are actually created earlier (i.e. before the version that introduces that feature as optional is released). For example PEP 479: StopIteration handling inside generators:

  • 2014 年创建的 PEP
  • 3.5.0可选,2015年发布
  • 3.7必备,2018年发布

即使该功能在 2018 年成为强制性功能,计划(其 PEP)早在很久以前就已创建。

__future__ docs 很好地概述了某项功能何时可用。并非所有功能都已反向移植到 Python 的所有(次要)版本,即使它们支持 __future__ 导入。这是因为在发布这些次要版本后才可以使用这些功能。