Python future模块

来源:互联网 发布:yum配置文件 编辑:程序博客网 时间:2024/05/03 16:28

Python编程语言中有很多比较有用的模块,这些模块在实际使用中可以帮助我们轻松的完成许多功能需求。我们今天将会在这里通过对Python future模块的了解,来对这方面的知识做一个详细的了解。

今天在学习Python Cookbook的时候,发现一句语法from future import division,很奇怪future这个名字,网上搜了一下,原来是很有用的一个模块。

详细说明见这里。按照官方的解释,至少确保在2.1之前版本的Python可以正常运行一些新的语言特性,需要使用语句
‘from future import *’。举例来说:

Enable nested scopes in Python2.1
from future import nested_scopes
如果使用这个语句,则该语句必须是模块或程序的第一个语句。此外,’_ future_’ 模块中存在的特性最终将成为Python语言标准的一部分。到那时,将不再需要使用Python future模块。

Python future模块的更多示例:

1. Python 2.6中也有一个 future import 使得所有的字符串文本成为Unicode字符串。这就意味着\u转义序列可以用于包含Unicode字符。

from future import unicode_literals
s = (‘\u751f\u3080\u304e\u3000\u751f\u3054’
‘\u3081\u3000\u751f\u305f\u307e\u3054’)
print len(s) # 12 Unicode characters
2. Python 2.6可以通过 import future 来将print从语言语法中移除,让你可以使用函数的形式。例如:

from future import print_function
print(‘# of entries’, len(dictionary), file=sys.stderr)
3. 整数除法

python 2.5中:23/6 # 得3
from future import division 之后:
23/6 # 得 3.8333333333333335
参考:http://developer.51cto.com/art/201003/186805.htm

0 0