__future__模块如何在Python 2.7中运行?

How does the __future__ module work in Python 2.7?

本问题已经有最佳答案,请猛点这里访问。

在使用__future__模块和print_function的python 2.7中,可以使用python 3.x打印功能。我的问题是,Python的开发人员如何知道将来的Python版本中会发生什么?或者这个模块是在发布后添加到python 2.7中的?下面是我要说的代码:

1
2
from __future__ import print_function
print("Hello world!")


python 2.1中引入了__future__模块,以便访问即将出现的特性/功能,这些特性/功能将导致与当前实现不兼容,并在需要时扩展到每个版本。

因此,该模块提供了在早期版本中使用未来版本的不兼容功能的可能性。因此,您可以利用这些功能即将到来的优势。

如文档中所述,该模块有三个主要原因:

__future__ is a real module, and serves three purposes:

  • To avoid confusing existing tools that analyze import statements and
    expect to find the modules they’re importing.
  • To ensure that future
    statements run under releases prior to 2.1 at least yield runtime
    exceptions (the import of __future__ will fail, because there was no
    module of that name prior to 2.1).
  • To document when incompatible
    changes were introduced, and when they will be — or were — made
    mandatory. This is a form of executable documentation, and can be
    inspected programmatically via importing __future__ and examining its
    contents.