Newbie: Object assignment return value
Hans Nowak
wurmy at earthlink.net
Thu Feb 14 14:45:34 EST 2002
Dean Goodmanson wrote:
>
> (I think) I'm trying to understand if object assignment has a return value.
>
> Scenario A:
> >>> str( spam= 5 )
> ''
I don't know how you got this to work. In 2.1 I get:
>>> str(spam=5)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in ?
str(spam=5)
TypeError: str() takes no keyword arguments
>>>
and in 2.2:
>>> str(spam=5)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in ?
str(spam=5)
TypeError: 'spam' is an invalid keyword argument for this function
>>>
> >>> str((spam=5))
> File "<stdin>", line 1
> str((spam=5))
> ^
> SyntaxError: invalid syntax
f(a=1) for a function f, is treated like f is called with
keyword argument a. That's why str(spam=5) didn't yield a
*syntax* error. When you put parentheses around it, it
cannot be mistaken for a keyword argument anymore, and
you end up with passing a binding (or "assignment" as
some call it, although this isn't really correct) as a
parameter to the function, which is simply not valid
syntax.
> >>> # continued : Scenario B:
> >>> print spam
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> NameError: name 'spam' is not defined
Even if your str(spam=5) succeeds, it does not do what
you expect. This is not an "assignment" passed to a function.
It's a keyword argument, and no new variable/name is
created (unless the function happens to do some nasty
hackery, but let's not go there).
To answer your original question: no, "assignment" does
not return a value. You can chain them, but that's as good
as it gets:
>>> a = b = c = 42
>>> a, b, c
(42, 42, 42)
>>>
but any other things you might be familiar with (from,
for example, C) won't work:
>>> a = (b = 12)
SyntaxError: invalid syntax
>>> if x = "foo": print "bar"
SyntaxError: invalid syntax
Note that this does prevent you from the common mistake
made in C, writing if (x = y) where you really meant
if (x == y). <smile>
> B: What happend to my spam?
> Espcially when this works:
> >>> str(int())
> '0'
> >>> str((int()))
> '0'
> >>>
These are different cases... int() is an expression and
can be passed to str just fine.
--
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
More information about the Python-list
mailing list