2

For Python2x If we use,

from __future__ import print_function

the print will become function which is previously the keyword

But practically,

How two of these are different ?

I can still use print the same way as I was using it when it was a keyword, then what difference does it make and how could it be more efficient than before ?

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110

2 Answers2

9

Here you can read some official documentation with examples and PEP3105 with more details.

As quick differences, there are several things which are very easy to do with print function (Python 3 or from __future__ import print_function) or at least very consistently:

No newline

print('Hello!', end='')

That was more complicated in python 2.

Print to stderr

import sys
print('ERROR!!!!!', file=sys.stderr)

In python 2.

Community
  • 1
  • 1
Diego Herranz
  • 2,857
  • 2
  • 19
  • 34
7

Not really. With the function you must do print(stuff), but with the statement you can do print stuff.

The main advantage is that, if print is a function, you can assign a different function to that name. For instance, you could create a new function that not only outputs the data to the screen but also logs it to a file. If you assign this function to the builtin print, then any code that uses print will automatically log to a file. This is not possible with print as a statement, and you must resort to other techniques to get the same effect.

There are also some smaller changes associated with the way print formats its output. The statement used "magic" syntax (e.g., a trailing comma suppressed a following space), while the function uses standard keyword-argument conventions.

Also, print is always a function in Python 3. It's in Python 2 that you must use the __future__ import if you want print as a function.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • but that doesn't make it any better ? now, does it ? – Sufiyan Ghori Oct 18 '13 at 16:45
  • Always remember that "better" is relative. Just because a software feature doesn't appear to directly benefit your projects doesn't mean that it brings no benefits to (possibly thousands of) others. What works for one doesn't necessarily work for others and vice-versa. – JS. Oct 18 '13 at 17:27