The role of from __future__ import


Summary: The purpose of this line of code is to use the higher version features in the lower version of python, and call the features in python3 in python2 . For example, the print_function implementation uses the print() command in 3.x in 2.x.

1、absolute_import

from __future__ import absolute_import

This is a statement that imports the 3.x import feature in py2.x. It is used to distinguish between absolute import and relative import. It is
declared as an absolute reference.

In Python 2.4 or before, the default is relative reference, that is, first look for the module in this directory. But if there is a module name in this directory that conflicts with the system (sys.path) module with the same name, and you want to reference the system module, this statement will work.

For details, please see: https://blog.csdn.net/happyjacob/article/details/109348379

2、division

from __future__ import division

In python3, the default is exact division, which is the same as the concept of division in mathematics, while the default in python2 is divisible. If you want to use exact division in python2, use this statement to declare.

>>> 3/4
0
>>> from __future__ import division
>>> 3/4
0.75

3、print_function

from __future__ import print_function

Use python3's print function in python2

>>> print("a")
a
>>> print "a"
a
>>>
>>> from __future__ import print_function
>>> print("a")
a
>>> print "a"
  File "<stdin>", line 1
    print "a"
            ^
SyntaxError: invalid syntax

print2 supports print "a" and print("a"), print3 only supports print("a"), after using from __future__ import print_function, python2 can only write print("a")

Guess you like

Origin blog.csdn.net/happyjacob/article/details/109396117