Python中的“未来”是什么,如何使用它,何时使用它,以及它是如何工作的

2024-03-29 07:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

__future__经常出现在Python模块中。我不明白__future__的用途以及如何使用它,甚至在阅读the Python's ^{} doc之后。

有人能举例说明吗?

关于__future__基本用法的一些回答似乎是正确的。

不过,关于__future__如何工作,我还需要了解一件事:

最让我困惑的概念是,当前的python版本如何包含将来版本的特性,以及如何在当前版本的python中成功编译使用将来版本特性的程序。

我猜当前的版本已经打包了未来的潜在特性。但是,这些功能只有通过使用__future__才可用,因为它们不是当前的标准。如果我是对的,请告诉我。


Tags: 模块the程序功能版本概念用法标准
3条回答

通过__future__模块的包含,您可以慢慢习惯不兼容的更改或引入新关键字的更改。

例如,要使用上下文管理器,必须在2.5中执行from __future__ import with_statement,因为with关键字是新的,不应该再用作变量名。为了在Python 2.5或更早版本中使用with作为Python关键字,需要使用上面的导入。

另一个例子是

from __future__ import division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

如果没有__future__内容,两个print语句都将打印1

内部区别在于,如果没有导入,/将映射到__div__()方法,而使用__truediv__()方法。(无论如何,//调用__floordiv__()。)

Aproposprintprint成为3.x中的函数,失去作为关键字的特殊属性。所以情况正好相反。

>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>

__future__是一个伪模块,程序员可以使用它来启用与当前解释器不兼容的新语言功能。例如,表达式11/4当前的计算结果为2。如果执行它的模块通过执行以下命令启用了真正的除法:

from __future__ import division

表达式11/4的计算结果为2.75。通过导入__future__模块并对其变量求值,您可以看到新功能何时首次添加到语言中,以及何时成为默认功能:

  >>> import __future__
  >>> __future__.division
  _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

当你这样做的时候

from __future__ import whatever

实际上,您使用的不是import语句,而是future statement。你读错了文档,因为你实际上并没有导入那个模块。

未来的语句是特殊的——它们改变了Python模块的解析方式,这就是为什么它们必须位于文件的顶部。它们赋予文件中的单词或符号新的或不同的含义。从文档中:

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

如果您真的想导入__future__模块,只需

import __future__

然后照常访问。

相关问题 更多 >