1

How can I return a print function in Python 2.7? In Python 3 you can type return print(True), but in Python 2.7 I get an invalid syntax error when I try return print True. I'm new to Python.

5
  • 1
    Why do you want to return a print function? Commented Jan 7, 2013 at 21:27
  • Try parenthesis: return (print True) Commented Jan 7, 2013 at 21:29
  • I just want to! I thought it was interesting that it was possible in python3 but I have no idea how to implement that in python2.7 and return (print True) does not work Commented Jan 7, 2013 at 21:29
  • 4
    You're not actually returning the print function in 3.x; you're returning the result of calling the print function, which is always just None. Commented Jan 7, 2013 at 21:47
  • @abarnert is correct. If you want to return the print function, it will simply be return print (but that would not work in Python 2.x) Commented Jan 8, 2013 at 0:09

3 Answers 3

9

In Python 2.x print is not a function, but a keyword. The possible best solution would be importing 3.x-like print behvaiour as follows:

from __future__ import print_function p = print # now you can store the function reference to a variable p('I am a function now!') >>> I am a function now! def get_print(): return print # or return it :) get_print() >>> <function print> 
Sign up to request clarification or add additional context in comments.

Comments

2

That's not possible with Python 2.7 because print is not a function, it is a reserved word*. You can easily make a function for it just like this:

def printf(x): print x 

And then you can do what you wish:

return (printf(True)) 

But you have to do that renaming.

*That's one of the things that were solved more elegantly on python 3.

Comments

0

print, being a statement rather than a function in Python 2, cannot be used in this way. Rather, you need to do this:

from __future__ import print_function def foo(): return print(True) foo() 

3 Comments

Why True in print(True)? oO
@BasicWolf Cause that was in the original question
Ah, sorry, my bad. Time for me to go to bed :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.