To get the 3.0 print function we do the following in Python 2.6:
from __future__ import print_function
But to use the function we invoke print() not print_function(). Is this just an inconsistency or is there a good reason for this?
Why not the following:
from __future__ import print
In Python 3, the keyword
print
has been changed from calling a statement to calling a function.So instead of saying
print value
you now need to sayprint(value)
, or you'll get aSyntaxError
.By doing the
import
, this change is effected in Python 2, too, so you can write programs using the same syntax as Python 3 (at least as far asprint
is concerned).Minimal example
As mentioned at: What is __future__ in Python used for and how/when to use it, and how it works
from __future__
are magic statements that alter how Python parses code.from __future__ import print_function
in particular changesprint
from a statement into a built-in function, as shown in the interactive shell above.Why
print(1)
works withoutfrom __future__ import print_function
in Python 2Because the:
is parsed as:
print
statementinstead of:
print()
functionAnd:
as mentioned at: Python tuple trailing comma syntax rule
The reason is that when you import from
__future__
you're really just setting a flag that tells the interpreter to behave a bit differently than usual -- in the case ofprint_function
, theprint()
function is made available in place of the statement. The__future__
module is thus "special" or "magic" -- it doesn't work like the usual modules.print_function
is aFeatureName
not be confused with theprint
built-in function itself. It is a feature that is available from the future so that you can use the built-in function that it can provide.Other Features include:
There are specific reasons as when you migrate your code to next higher version, your program will remain as such as use the updated feature instead of the
__future__
version. Also if it were function name or the keyword itself, it may cause confusion to the parser.Simple. print is keyword in Python 2.
So a statement like
would be an automatic SyntaxError in Python 2.
Allowing (hardcoding it in the syntax)
was deemed not worth the effort.
For completness, all the currently available features are: