933

__future__ frequently appears in Python modules. I do not understand what __future__ is for and how/when to use it even after reading the Python's __future__ doc.

Can anyone explain with examples?

A few answers regarding the basic usage of __future__ I've received seemed correct.

However, I need to understand one more thing regarding how __future__ works:

The most confusing concept for me is how a current python release includes features for future releases, and how a program using a feature from a future release can be be compiled successfully in the current version of Python.

I am guessing that the current release is packaged with potential features for the future. However, the features are available only by using __future__ because they are not the current standard. Let me know if I am right.

2
  • 15
    This is the original proposal for the future statement. I found it helpful in understanding why it's there in the first place and so when and how to use it follow naturally. python.org/dev/peps/pep-0236 Commented Mar 2, 2015 at 3:49
  • 7
    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. Commented Nov 27, 2018 at 11:01

9 Answers 9

527

With __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 division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

Without the __future__ stuff, both print statements would print 1.

The internal difference is that without that import, / is mapped to the __div__() method, while with it, __truediv__() is used. (In any case, // calls __floordiv__().)

Apropos print: print becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.

>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>
9
  • 189
    don't forget from __future__ import braces :p
    – mdeous
    Commented Aug 16, 2011 at 8:22
  • 14
    @zoogleflatt If you are more of a tab guy, you don't know PEP 8. It is strongly recommended to not use tabs...
    – glglgl
    Commented Mar 3, 2015 at 19:29
  • 5
    @glglgl Well technically it just says they're preferred. It wasn't entirely clear to me after reading why this is exactly, I'm guessing it's to have indent levels match up exactly to make code neater? Commented Mar 6, 2015 at 7:03
  • 4
    @zoogleflatt It surely has also to do with the fact that most people use 4 spaces for 1 level of indentation, that for compatibility reasons one tab is equivalent to 8 spaces and mixing tabs and spaces is discouraged (resp., AFAIK, even disallowed in Py3)
    – glglgl
    Commented Mar 6, 2015 at 8:45
  • 1
    @whiteSkar I am currently not up to date with newer versions of python 3, but I assume that it is still in use, just that you don't probably need it with these quite old features. In Python 3, print is definitely a function, but there may be other features which might use __future__. (Edit: see docs.python.org/3/library/__future__.html where it is still used.)
    – glglgl
    Commented Apr 30, 2020 at 6:50
247

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

import __future__

and then access it as usual.

1
  • 8
    Technically, it is also an import statement, as the relevant name is bound to a local variable. from __future__ import print_function both changes the behavior of the print keyword and has a runtime affect equivalent to print_function = __import__("__future__").print_function
    – pppery
    Commented Jul 17, 2017 at 1:19
149

__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

the expression 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)
2
  • 2
    So, based on the release version in the variables, if your interpreter is using a later version than indicate, the import __future__ xyz is a no-op?
    – Ray
    Commented Apr 15, 2016 at 15:15
  • 7
    It is somewhat analogous to a polyfill in the browser world
    – cs01
    Commented Dec 2, 2016 at 18:37
74

There are some great answers already, but none of them address a complete list of what the __future__ statement currently supports.

Put simply, the __future__ statement forces Python interpreters to use newer features of the language.


The features that it currently supports are the following:

nested_scopes

Prior to Python 2.1, the following code would raise a NameError:

def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...

The from __future__ import nested_scopes directive will allow for this feature to be enabled.

generators

Introduced generator functions such as the one below to save state between successive function calls:

def fib():
    a, b = 0, 1
    while 1:
       yield b
       a, b = b, a+b

division

Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y, whereas floor division is specified by x//y.

The from __future__ import division directive forces the use of Python 3.0 style division.

absolute_import

Allows for parenthesis to enclose multiple import statements. For example:

from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
    LEFT, DISABLED, NORMAL, RIDGE, END)

Instead of:

from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
    LEFT, DISABLED, NORMAL, RIDGE, END

Or:

from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END

with_statement

Adds the statement with as a keyword in Python to eliminate the need for try/finally statements. Common uses of this are when doing file I/O such as:

with open('workfile', 'r') as f:
     read_data = f.read()

print_function:

Forces the use of Python 3 parenthesis-style print() function call instead of the print MESSAGE style statement.

unicode_literals

Introduces the literal syntax for the bytes object. Meaning that statements such as bytes('Hello world', 'ascii') can be simply expressed as b'Hello world'.

generator_stop

Replaces the use of the StopIteration exception used inside generator functions with the RuntimeError exception.

One other use not mentioned above is that the __future__ statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.


References

4
  • 3
    Assuming you are offline how does python know whether a future version is available or not? And how does it use future features if you have not installed future version of python on your computer? Commented May 9, 2019 at 7:57
  • 6
    @MohsenHaddadi The future statement is somewhat like a feature flag... When certain features are accepted into Python that change the behavior of existing programs (like true division, for example), first you are able to enable them with the future statement, and then in a future version they become a permanent feature of the language. Hence the name __future__. I believe that this ability to opt into breaking changes early is meant to help existing programs transition in a timely manner, before the breaking change is put into full effect.
    – Dev
    Commented Jun 20, 2020 at 9:12
  • 2
    I think this is the best answer. especially the start of the answer, "force" to use "newer features". Commented Nov 5, 2020 at 10:21
  • 1
    Excellent answer, I just wish there was an from __past__ import print as I really liked the laziness of Python 2's print quick_debug_var Commented Mar 23, 2021 at 6:15
66

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)
0
29

Or is it like saying "Since this is python v2.7, use that different 'print' function that has also been added to python v2.7, after it was added in python 3. So my 'print' will no longer be statements (eg print "message" ) but functions (eg, print("message", options). That way when my code is run in python 3, 'print' will not break."

In

from __future__ import print_function

print_function is the module containing the new implementation of 'print' as per how it is behaving in python v3.

This has more explanation: http://python3porting.com/noconv.html

5

One of the uses which I found to be very useful is the print_function from __future__ module.

In Python 2.7, I wanted chars from different print statements to be printed on same line without spaces.

It can be done using a comma(",") at the end, but it also appends an extra space. The above statement when used as :

from __future__ import print_function
...
print (v_num,end="")
...

This will print the value of v_num from each iteration in a single line without spaces.

5

__future__ is a python module. It was added to avoid confusing existing tools that analyzed import statements and expected to find the modules they’re importing. It was added in version 2.1 so import of __future__ will fail if used prior to version 2.1.

Now see this code:

>>> from __future__ import division
>>> division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 131072)

The division returned in the format of _Feature(OptionalRelease, MandatoryRelease, CompilerFlag). OptionalRelease and MandatoryRelease are both 5-tuples in form of:

(
 PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)

So in our case, OptionalRelease is 2.2.0a2 and MandatoryRelease is 3.0.0a0.

OptionalRelease tells us the first release when the feature was accepted.

MandatoryRelease predicts when will the feature be part of the language or shows when the feature became part of the language; in releases at or after that, modules no longer need a future statement to use the feature in question, but may continue to use such imports. If MandatoryRelease is None then that planned feature is dropped.

CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the built-in function compile() to enable the feature in dynamically compiled code. This flag is stored in the compiler_flag attribute on _Feature instances.

-4

After Python 3.0 onward, print is no longer just a statement, its a function instead. and is included in PEP 3105.

Also I think the Python 3.0 package has still these special functionality. Lets see its usability through a traditional "Pyramid program" in Python:

from __future__ import print_function

class Star(object):
    def __init__(self,count):
        self.count = count

    def start(self):
        for i in range(1,self.count):
            for j in range (i): 
                print('*', end='') # PEP 3105: print As a Function 
            print()

a = Star(5)
a.start()

Output:
*
**
***
****

If we use normal print function, we won't be able to achieve the same output, since print() comes with a extra newline. So every time the inner for loop execute, it will print * onto the next line.

Not the answer you're looking for? Browse other questions tagged or ask your own question.