python – What is the __future__ module for?

Question:

I've seen in some code written in Python the following declaration:

 from __future__ import print_function

What is the purpose of this __future__ module? When do I need to import it into a script I'm doing?

Why is it, unlike other modules, written as if it were a magic property (the underlines before and after)?

Answer:

The __future__ module really is a bit magical. It would be more accurate to see the from __future__ import as a declaration for the Python compiler rather than a typical import .

The raison d'être of from __future__ import is to make available functionality planned for future versions of Python but which cannot be the default behavior of the language yet to preserve compatibility with existing programs.

For example, in Python 2 print is a command that is called without parentheses:

print "Oi Mundo"

In Python 3, print now a normal function, called with parentheses

print("Oi Mundo")

To ease this transition, as of Python 2.6, print as a function is an optional feature. The default in Python 2.6 is for print to be a command but if you use from __future__ import print_function then print becomes a function.

For more information, see PEP 236 , which proposed __future__ , and the section on future statements in the official documentation.

Scroll to Top