The role of from __future__ import


Summary: The function of this line of code is introduced to use high-version features in low-version python, calling features in python3 in python2 , such as print_function to use the print() command in 3.x in 2.x.

1、absolute_import

from __future__ import absolute_import

This is a statement that imports the import feature of 3.x in py2.x, to distinguish between absolute and relative imports
declared as absolute references.

Python 2.4 or earlier defaults to relative references, that is, first look for modules in this directory. But if there is a module name in this directory that conflicts with a system (sys.path) module with the same name, and you want to refer to a system module, this declaration will work.

See: https://blog.csdn.net/happyjacob/article/details/109348379

2、division

from __future__ import division

The default in python3 is exact division, which is the same as the concept of division in mathematics, while the default in python2 is integer division. 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

Using 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 the writing method of print "a" and print("a"), print3 only supports the writing method of print("a"), after using from __future__ import print_function, python2 can only write the writing method of print("a")