Reputation: 1965
In python everything is an object and you can pass it around easily.
So I can do :
>> def b():
....print "b"
>> a = b
>> a()
b
But if I do
a = print
I get SyntaxError
. Why so ?
Upvotes: 9
Views: 675
Reputation: 142136
In Python 2.x, print is a statement not a function. In 2.6+ you can enable it to be a function within a given module using from __future__ import print_function
. In Python 3.x it is a function that can be passed around.
Upvotes: 20
Reputation: 309891
The other answers are correct. print
is a statement, not a function in python2.x. What you have will work on python3. The only thing that I have to add is that if you want something that will work on python2 and python3, you can pass around sys.stdout.write
. This doesn't write a newline (unlike print
) -- it acts like any other file object.
Upvotes: 4
Reputation: 37441
In python2, print
is a statement. If you do from __future__ import print_function
, you can do as you described. In python3, what you tried works without any imports, since print was made a function.
This is covered in PEP3105
Upvotes: 6
Reputation: 39548
print
is not a function in pre 3.x python. It doesn't even look like one, you don't need to call it by (params)
Upvotes: 3