Tag Archives: __future__

From in Python__ future__ The role of import *

when we read the code, we always see it beginning with the words from __import * with ___. What this does is introduce the features of the new version into the current version, meaning that we can use some of the features of the new version in the current version.

For example, in python2.x and python3.x the standard way of writing print is

# python 2.x
print "Hello World"

# python 3.x
print("Hello World")

If you want to use python2.x to experience python3.x, use the import print_function from ___ future__,

# python 2.x
from __future__ import print_function
print("Hello World")

and in that case if you go back to python2.x the standard way of writing it would be an error,

# python 2.x
from __future__ import print_function
print "Hello World"

>>> print "Hello World"
  File "<stdin>", line 1
    print "Hello World"
                      ^
SyntaxError: invalid syntax

in addition to the print function, the module with ___ future__ has many other functions,

1. Integer division

# python 2.x
5/2
>>> 2

from __future__ import division
5/2
>>> 2.5

2. With

# python 2.x
try:
    with open('test.txt', 'w') as f:
    f.write('Hello World')
finally:
    f.close()

# 用with替代上述异常检测代码:
from __future__ import with_statement
with open('test.txt', 'w') as f:
    f.write('Hi there!')

3. Absolute introduction (absolute_import)

Absolute

is mainly introduced for python2.4 and earlier versions which, when introducing a.py file, first look for it in the current directory. If so, the file in the current package is referenced first. If we want to reference python’s built-in.py file, we need to use

from __future__ import absolute_import