python进阶笔记【2】 --- 一个奇怪的 __future__ 库

写在前面

我是在学习cs231n的assignment3的课程,发现里面的代码大量频繁出现了这个库,那我就很奇怪了,为什么有个future这个奇怪名字的库会出现呢?到底这个库又有什么用?下面就让我为你揭开。

正文

总所周知,python3.x和python2.x根本就是两个东西,每次因为这个兼容性的问题都会把自己搞疯。

下面很多内容参考廖雪峰博客

从Python 2.7到Python 3.x就有不兼容的一些改动,比如2.x里的字符串用’xxx’表示str,Unicode字符串用u’xxx’表示unicode,而在3.x中,所有字符串都被视为unicode,因此,写u’xxx’和’xxx’是完全一致的,而在2.x中以’xxx’表示的str就必须写成b’xxx’,以此表示“二进制字符串”。

于是呢。

Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。举例说明如下:

为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过unicode_literals来使用Python 3.x的新的语法:

# still running on Python 2.7

from __future__ import unicode_literals

print '\'xxx\' is unicode?', isinstance('xxx', unicode)
print 'u\'xxx\' is unicode?', isinstance(u'xxx', unicode)
print '\'xxx\' is str?', isinstance('xxx', str)
print 'b\'xxx\' is str?', isinstance(b'xxx', str)


输出结果:

'xxx' is unicode? True
u'xxx' is unicode? True
'xxx' is str? False
b'xxx' is str? True

类似的情况还有除法运算。在Python 2.x中,对于除法有两种情况,如果是整数相除,结果仍是整数,余数会被扔掉,这种除法叫“floor deviation”:

>>> 10 / 3
3

要做精确除法,必须把其中一个数变成浮点数:

>>> 10.0 / 3
3.3333333333333335

而在Python 3.x中,所有的除法都是精确除法,floor deviation 用//表示:

$ python3
Python 3.3.2 (default, Jan 22 2014, 09:54:40) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3

如果你想在Python 2.7的代码中直接使用Python 3.x的除法,可以通过__future__模块的division实现:

from __future__ import division

print '10 / 3 =', 10 / 3
print '10.0 / 3 =', 10.0 / 3
print '10 // 3 =', 10 // 3

结果如下:

10 / 3 = 3.33333333333
10.0 / 3 = 3.33333333333
10 // 3 = 3

所以总结来说,__future__就好像这个名字一样,未来,就是为了让你在python2.x的情况下使用python3.x的东西,具体还有很多的详细使用方式就需要好好看看api了。

api传送门
feature不多,才7个。

    原文作者:jasperyang
    原文地址: https://segmentfault.com/a/1190000010857744
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞