作用
__future__模塊提供某些將要引入的特性
2.7.5的__future__
基本上是python3中的特性
有以下內容
In [1]: import __future__ In [2]: __future__. __future__.CO_FUTURE_ABSOLUTE_IMPORT __future__.all_feature_names __future__.CO_FUTURE_DIVISION __future__.division __future__.CO_FUTURE_PRINT_FUNCTION __future__.generators __future__.CO_FUTURE_UNICODE_LITERALS __future__.nested_scopes __future__.CO_FUTURE_WITH_STATEMENT __future__.print_function __future__.CO_GENERATOR_ALLOWED __future__.unicode_literals __future__.CO_NESTED __future__.with_statement __future__.absolute_import In [2]: __future__.
可導入的功能有哪些?
In [3]: import __future__ In [4]: __future__.all_feature_names Out[4]: ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals']
對應功能如下
division 新的除法特性,本來的除號`/`對於分子分母是整數的情況會取整,但新特性中在此情況下的除法不會取整,取整的使用`//`。如下可見,只有分子分母都是整數時結果不同。
In [1]: 3 / 5 Out[1]: 0 In [2]: 3 // 5 Out[2]: 0 In [3]: 3.0 / 5.0 Out[3]: 0.6 In [4]: 3.0 // 5.0 Out[4]: 0.0 In [5]: from __future__ import division In [6]: 3 / 5 Out[6]: 0.6 In [7]: 3 // 5 Out[7]: 0 In [8]: 3.0 / 5.0 Out[8]: 0.6 In [9]: 3.0 // 5.0 Out[9]: 0.0
print_function 新的print是一個函數,如果導入此特性,之前的print語句就不能用了。
In [1]: print 'test __future__' test __future__ In [2]: from __future__ import print_function In [3]: print('test') test In [4]: print 'test' File "<ipython-input-4-ed4b06bfff9f>", line 1 print 'test' ^ SyntaxError: invalid syntax
unicode_literals 這個是對字符串使用unicode字符
In [1]: print '目錄' 鐩綍 In [2]: from __future__ import unicode_literals In [3]: print '目錄' 目錄
absolute_import 這個沒有搞懂,如果我當前目錄有一個sys.py,我用的時候總是會調用系統的sys。如果當前目錄和sys.path的路徑中都有一個foo,則都會調用當前目錄下的foo。另外,我運行的方式都是 python filename.py的方式,而如果使用python -c "import filename"則又是另一種答案。這個問題還沒有解決,搜到的最詳細的討論見http://bytes.com/topic/python/answers/596703-__future__-import-absolute_import
nested_scopes 這個是修改嵌套函數或lambda函數中變量的搜索順序,從`當前函數命名空間->模塊命名空間`的順序更改為了`當前函數命名空間->父函數命名空間->模塊命名空間`,python2.7.5中默認使用
generators 生成器,對應yield的語法,python2.7.5中默認使用
with_statement 是使用with關鍵字,python2.7.5是默認使用
運用
首先是可以做個性化的用法,比如你喜歡用print()而不是print
更重要的是基本用以下幾句就可以讓python2和python3有良好的兼容性了
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import