Why do we call print after import print_function (in Python 2.6)

To get the print function 3.0, we do the following in Python 2.6:

from __future__ import print_function 

But to use the function, we call print () not print_function (). Is it just inconsistency or is there a good reason for this?

Why not the following:

 from __future__ import print 
+59
python import
Dec 30 '10 at 7:24
source share
5 answers

The reason is that when importing from __future__ you really just set a flag that tells the interpreter to behave a little differently than usual - in the case of print_function , the print() function is available instead of using the statement. Thus, the __future__ module is "special" or "magic" - it does not work like regular modules.

+47
Dec 30 2018-10-12T00:
source share

print_function is FeatureName not to be confused with the most built-in print function. This is a feature available from the future, so you can use the built-in function that it can provide.

Other features include:

 all_feature_names = [ "nested_scopes", "generators", "division", "absolute_import", "with_statement", "print_function", "unicode_literals", ] 

There are certain reasons why when you transfer code to the next higher version, your program will remain the same as using the updated function instead of the __future__ version. Also, if it is a function name or a keyword in itself, it can cause confusion with the parser.

+10
Dec 30 '10 at 7:50
source share

Simple print is a keyword in Python 2.

So, a statement like

 from somewhere import print 

will be an automatic SyntaxError in Python 2.

Resolution (hard coding in syntax)

 from __future__ import print 

It was considered inappropriate.

+4
Nov 24 '15 at 12:28
source share

In Python 3, the print keyword was changed from a statement to a function call.

So instead of saying print value , you now need to say print(value) , or you get a SyntaxError .

By doing import , this change is also done in Python 2, so you can write programs using the same syntax as Python 3 (at least before print ).

+3
Dec 30 '10 at 7:26
source share

Minimal example

 >>> print # Statement. >>> from __future__ import print_function >>> print # Function object. <built-in function print> >>> print() # Function call. >>> 

As mentioned in: What is __future__ in Python that is used and how / when to use it, and how it works from __future__ are magical statements that change how Python parses the code.

from __future__ import print_function in particular, print changes from an instruction to an inline function, as shown in the interactive shell above.

Why print(1) works without from __future__ import print_function in Python 2

Because:

 print(1) 

analyzed as:

 print (1) ^^^^^ ^^^ 1 2 
  • print
  • Argument

instead:

 print( 1 ) ^^^^^^ ^ ^ 1 2 1 
  • print() function
  • Argument

and

 assert 1 == (1) 

as mentioned in: Correct comma syntax rule for Python tuple

0
Aug 04 '16 at 10:08 on
source share



All Articles