Fra*_*ank 9 python python-module python-2.6 python-3.x
我开始学习Python,但我不得不使用v2.6.2解释器.
我希望尽可能接近Python 3,例如,使用新print函数,"true"除法等.
from __future__ import division
from __future__ import print_function
print(1/2, file=sys.stderr) # 0.5
Run Code Online (Sandbox Code Playgroud)
我应该从哪些其他功能导入__future__?
我想我可以做一般import __future__但是当我升级到更高版本(v2.7可能有更多功能__future__)时我会得到不同的行为,然后我的脚本可能会停止工作.
好吧,即使没有文档,__future__也是一个常规模块,它有一些关于它自己的信息:
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals']
>>> __future__.unicode_literals
_Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 131072)
Run Code Online (Sandbox Code Playgroud)
Python 2.6中有大部分已经启用的功能,因此可供选择division,print_function,absolute_import和unicode_literals.
不,import __future__不会像你想象的那样奏效.当您使用from __future__ import something表单作为文件中的第一个语句时,这是唯一的魔力.有关更多信息,请参阅文档.
当然,无论你输入多少__future__,你都会在3.x中获得不同的行为.
我应该从哪些其他功能导入
__future__?
要获得最新的行为,您当然应该导入__future__所提供的所有功能,除了您获得的功能.(系统设置的方式,旧功能即使在它们始终开启后也不会掉线.)
请注意,import __future__会不会给你的一切,也不会from __future__ import *.该from ... import ...语法是特例,对于__future__(这是它如何工作的),但__future__仍是可以用导入一个真正的模块import __future__.但是,这样做会让您知道实际的功能名称,以及它们何时(或预期)默认的信息,以及它们何时可用.
>>> [
... name for name in __future__.all_feature_names if
... getattr(__future__, name).optional <=
... sys.version_info <
... getattr(__future__, name).mandatory
... ]
['division', 'print_function', 'unicode_literals']
Run Code Online (Sandbox Code Playgroud)
是我在2.7.2得到的.