What is the __future__module for?

Asked

Viewed 3,361 times

20

I’ve seen it in some codes written in Python the following statement:

 from __future__ import print_function

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

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

1 answer

20


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

The raison d'être of from __future__ import is to provide features planned for future versions of Python but that may not be the default behavior of the language 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"

Already in Python 3, the print became a normal function, called with parentheses

print("Oi Mundo")

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

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

  • @mgibsonbr I also think he meant "No parentheses"

  • ops! s/spaces/parentheses/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.