Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How come print cannot be assigned to a variable?

0 views
Skip to first unread message

anonym...@gmail.com

unread,
May 20, 2005, 10:40:42 AM5/20/05
to
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

Adriano Ferreira

unread,
May 20, 2005, 10:47:42 AM5/20/05
to pytho...@python.org
print is a statement, not a function.

Read Guido's words on that:
http://www.python.org/search/hypermail/python-1992/0112.html

Regards.
Adriano.

anonym...@gmail.com

unread,
May 20, 2005, 12:51:40 PM5/20/05
to
Thank You Adriano. You were a huge help.

Vaibhav

John Doe

unread,
May 22, 2005, 7:55:37 PM5/22/05
to

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]

Steven Bethard

unread,
May 22, 2005, 11:45:19 PM5/22/05
to
John Doe wrote:
> 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

0 new messages