Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we invoke print after importing print_function (in Python 2.6)

Tags:

python

import

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 
like image 494
H2ONaCl Avatar asked Dec 30 '10 07:12

H2ONaCl


People also ask

What does from __ future __ import Print_function do?

from __future__ import print_function ... print (v_num,end="") ... This will print the value of v_num from each iteration in a single line without spaces.

Why is print a function in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

What happens when you print a function in Python?

The Python print() function takes in any number of parameters, and prints them out on one line of text. The items are each converted to text form, separated by spaces, and there is a single '\n' at the end (the "newline" char). When called with zero parameters, print() just prints the '\n' and nothing else.

What happens during Python import?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


2 Answers

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 of print_function, the print() 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.

like image 76
kindall Avatar answered Oct 19 '22 15:10

kindall


print_function is a FeatureName not be confused with the print 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:

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

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.

like image 27
Senthil Kumaran Avatar answered Oct 19 '22 17:10

Senthil Kumaran