from __future__ import包的作用

时间:2021-08-24 15:14:24

__future__是python2的概念,其实是为了使用python2时能够去调用一些在python3中实现的特性

1.absolute_import

from __future__ import absolute_import

这是一个在py2.x中导入3.x的导入特性的语句, 是为了区分出绝对导入和相对导入

声明为绝对引用。因为在Python 2.4或之前默认是相对引用,即先在本目录下寻找模块。但是如果本目录中有模块名与系统(sys.path)模块同名冲突,而想要引用的是系统模块时,该声明就能够起作用了。这样你调用import string时引入的就是系统的标准string.py,调用from pkg import string来引入当前目录的string.py

⚠️但是其实最好是不要声明与系统模块同名的模块,如果实在需要同名,最好使用from XXX import XXX来导入

2.division

from __future__ import division

在python3中默认是精确除法,而python2中默认的是截断式除法,如果在python2想要使用精确除法,就使用这个语句来声明

在python2中如果没有声明,那么除法默认的是截断式除法,如:

(deeplearning2) userdeMBP:~ user$ python
Python 2.7. |Anaconda, Inc.| (default, Dec , ::)
[GCC 4.2. Compatible Clang 4.0. (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> / >>> from __future__ import division
>>> /
0.75

当然,如果这个时候你想要使用截断式除法,为:

>>> //

3.print_function

from __future__ import print_function

即在python2中使用python3的print函数

>>> print 'now in python2 it is right'
now in python2 it is right
>>> print('now in python2 it is right too')
now in python2 it is right too >>> from __future__ import print_function
>>> print 'now in python2 it is wrong'
File "<stdin>", line
print 'now in python2 it is wrong'
^
SyntaxError: invalid syntax
>>> print('now in python2 it is right')
now in python2 it is right

可见导入了后,使用python2的print则会报错