Python中的__future__模块

我们经常在Python的项目中有如下语句:

from __future__ import unicode_literals, print_function, division

__future__模块中包含了Python未来将会支持的一些语言特性,通过import可以把新版本的特性引入到老版本中。

feature optional in mandatory in effect
nested_scopes 2.1.0b1 2.2  PEP 227: Statically Nested Scopes
generators 2.2.0a1 2.3  PEP 255: Simple Generators
division 2.2.0a2 3.0  PEP 238: Changing the Division Operator
absolute_import 2.5.0a1 3.0  PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6  PEP 343: The “with” Statement
print_function 2.6.0a2 3.0  PEP 3105: Make print a function
unicode_literals 2.6.0a2 3.0  PEP 3112: Bytes literals in Python 3000

因为我们常用的Python版本为2.7,从上表可以看到 division、print_function、unicode_literals等几个都是在2.x中未引入的,所以我们会用到

from __future__ import unicode_literals, print_function, division

这样的语句。
 
这里讲下这几个__future__中的模块的功能:
1.division是让Python支持精确地除法。在Python3.0以前,2/3 == 0.
2.print_function是把print从Python的关键字中去掉,用print()函数取而代之。
3.unicode_literals。所有字符串都是unicode,即使不在字符串前面加u。

Leave a Reply