What is __future__ in Python used for and how/when to use it, and how it works
__future__ module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do
from __future__ import with_statement in 2.5, as the
with keyword was new and shouldn't be used as variable names any longer. In order to use
with as a Python keyword in Python 2.5 or older, you will need to use the import from above.
Another example is
from __future__ import divisionprint 8/7 # prints 1.1428571428571428print 8//7 # prints 1
__future__ stuff, both
The internal difference is that without that import,
/ is mapped to the
__div__() method, while with it,
__truediv__() is used. (In any case,
printfrom __future__ import print_functionprint<built-in function print>>>>
When you do
from __future__ import whatever
You're not actually using an
import statement, but a future statement. You're reading the wrong docs, as you're not actually importing that module.
Future statements are special -- they change how your Python module is parsed, which is why they must be at the top of the file. They give new -- or different -- meaning to words or symbols in your file. From the docs:
A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.
If you actually want to import the
__future__ module, just do
and then access it as usual.
__future__ is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. For example, the expression
11/4 currently evaluates to
2. If the module in which it is executed had enabled true division by executing:
from __future__ import division
11/4 would evaluate to
2.75. By importing the
__future__ module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default:
import __future__ __future__.division_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)