Detailed explanation of Python module future usage principle

Time:2020-5-22

This article mainly introduces the detailed explanation of the future usage principle of Python module. In this article, the example code is introduced in great detail, which has certain reference learning value for your study or work. You can refer to the following for friends who need it

Computer knowledge is too much, many things are a detailed accumulation process in the use process. Recently, I met a long-term problem about future. I stepped on the pit, so I will make a note here, so as not to make similar mistakes in the future.

Function of future: import the features of the next new version into the current version, so we can test some features of the new version in the current version. To put it plainly, you can use the new version of Python without updating the version of Python and adding this module directly. Here are a few examples to illustrate its usage:

Python 2. X print is not a function. Help cannot be used. Python 3. X print is a function. Help can be used. At this time, you can see the benefits of future:

code:


# python2
#from __future__ import absolute_import, division, print_function
#print(3/5)
#print(3.0/5)
#print(3//5)
help(print)

Operation result:


➜ future git:(master) ✗ python future.py
 File "future.py", line 8
  help(print)
       ^
SyntaxError: invalid syntax

The error is reported because python2 does not support this syntax.

Just open the comment in the second line:


# python2
from __future__ import absolute_import, division, print_function
#print(3/5)
#print(3.0/5)
#print(3//5)
help(print)

The results are as follows:


Help on built-in function print in module __builtin__:

print(...)
  print(value, ..., sep=' ', end='\n', file=sys.stdout)
  
  Prints the values to a stream, or to sys.stdout by default.
  Optional keyword arguments:
  file: a file-like object (stream); defaults to the current sys.stdout.
  sep: string inserted between values, default a space.
  end: string appended after the last value, default a newline.

Another example: about division:


# python2
#from __future__ import absolute_import, division, print_function

print(3/5)
print(3.0/5)
print(3//5)
#help(print)

result:


➜ future git:(master) ✗ python future.py
0.6

Open the compiled macro, and the operation result is:


➜ future git:(master) ✗ python future.py
0.6
0.6

Look, the syntax of Python 3. X is ready to use.

With these two examples, it is estimated that your usage of future will be clear.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.