Return value of an assignment statement?
Jeff Schwab
jeff at schwabcenter.com
Sat Feb 23 10:44:17 EST 2008
bruno.desthuilliers at gmail.com wrote:
>> 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()
>
> What you want is:
>
> for astring, afunc in ((some_string, do_something), (other_string,
> do_other_thing)):
> m = pat.match(astring)
> if m:
> afunc(m)
> break
> else:
> do_default_thing()
That looks like the first realistic alternative I've seen. I find the
flow a little hard to follow, but I think that's mostly just because I'm
not accustomed to the syntax.
Your approach fits in my head a little more comfortably if none of the
lines are longer than eighty columns, if the for-loop isn't given an
else-clause (which still looks to my untrained eye like it should match
the preceding if), and if the break-statement is replaced with a
return-statement:
actions = (
('some_string', do_something),
('other_string', do_other_thing))
def find_action(pattern):
for string, action in actions:
m = pattern.match(string)
if m:
return action
return do_default_thing
find_action(re.compile('some pattern'))()
More information about the Python-list
mailing list