What is the __future__ module for?

12

I have seen in some codes written in Python the following statement:

 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 the other modules, written as if it were a magic property (the underlines before and after)?

    
asked by anonymous 03.05.2016 / 05:21

1 answer

12

The __future__ module really is a bit magic. It would be more accurate to see from __future__ import as a statement for the Python compiler instead of a typical import .

The rationale for from __future__ import is to provide planned functionality for future versions of Python, but it may not be the language's default behavior yet to preserve compatibility with existing programs.

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

print "Oi Mundo"

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

print("Oi Mundo")

To facilitate this transition, starting with Python 2.6, print as a function is an optional feature. The default in Python 2.6 is print being a command, but if you use from __future__ import print_function , print becomes a function.

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

    
03.05.2016 / 05:55