9

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 ?

4 Answers 4

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the future statement is explicit. It won't break any code because it affects only code that expects it in the same module
@J.F.Sebastian - thank you - I always confuse that with "A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session."
6

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

Comments

4

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.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.