Return value of an assignment statement?
Jeff Schwab
jeff at schwabcenter.com
Sat Feb 23 10:44:28 EST 2008
Jeff Schwab wrote:
> mrstephengross wrote:
>> Hi all. In C, an assignment statement returns the value assigned. For
>> instance:
>>
>> int x
>> int y = (x = 3)
>>
>> In the above example, (x=3) returns 3, which is assigned to y.
>>
>> In python, as far as I can tell, assignment statements don't return
>> anything:
>>
>> y = (x = 3)
>>
>> The above example generates a SyntaxError.
>>
>> Is this correct? I just want to make sure I've understood the
>> semantics.
>
> Yes, but there is valid syntax for the common case you mentioned:
>
> y = x = 3
>
> What you can't do (that I really miss) is have a tree of assign-and-test
> expressions:
>
> import re
> pat = re.compile('some pattern')
>
> if m = pat.match(some_string):
> do_something(m)
> else if m = pat.match(other_string):
> do_other_thing(m)
> else:
> do_default_thing()
This is apparently section 1.9 of the Python Cookbook:
http://www.oreilly.com/catalog/pythoncook2/toc.html
Martelli suggests something similar to the "thigamabob" technique I use
(he calls it DataHolder). It's really more like the "xmatch" posted by
Paul Rubin.
Martelli also says, though, that if you need this, you're not thinking
Pythonically. I don't know what the Pythonic alternative is. The
iterating-over-pairs approach suggested by Bruno is the only alternative
I've seen.
More information about the Python-list
mailing list