How come print cannot be assigned to a variable?

A

anonymousnerd

Hi all,
In Python, some functions can be assigned to variables like this:
length=len
Why is it that print cannot be assigned to a variable like this? (A
syntax error is declared.)

Thanks,

Vaibhav
 
J

John Doe

Hi all,
In Python, some functions can be assigned to variables like this:
length=len
Why is it that print cannot be assigned to a variable like this? (A
syntax error is declared.)

Thanks,

Vaibhav

print can't be assigned to variables since it's not a funcion, it's part
of the syntax of the language, like `for', `while', etc. and it can't be
assigned to variables, just as those can't be assigned.
If you need a function that prints stuff, consider these two examples:
[snip]
PrintFunc = lambda x: print x
[snip]
Or, a somewhat better solution:
[snip]
import sys
PrintFunc = sys.write
[snip]
 
S

Steven Bethard

John said:
If you need a function that prints stuff, consider these two examples:
[snip]
PrintFunc = lambda x: print x

py> printfunc = lambda x: print x
Traceback ( File "<interactive input>", line 1
printfunc = lambda x: print x
^
SyntaxError: invalid syntax

See Inappropriate use of Lambda on the Python Wiki[1]. This is also a
horrible idea as it means you can only print a single item:

py> print 1, 2, 3
1 2 3
py> def write(x):
.... print x
....
py> write(1, 2, 3)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: write() takes exactly 1 argument (3 given)
py> def write(*args):
.... print args
....
py> write(1, 2, 3)
(1, 2, 3)

The print statement has special spacing behavior. You could perhaps
approximate it with something like:

py> def write(*args):
.... for arg in args:
.... print arg,
.... print
....
py> write(1, 2, 3)
1 2 3

But why go to all this effort?

STeVe

[1] http://wiki.python.org/moin/DubiousPython
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top