Return value of an assignment statement?

Duncan Booth duncan.booth at invalid.invalid
Fri Feb 22 04:44:05 EST 2008


Carl Banks <pavlovevidence at gmail.com> wrote:

> Some Pythonistas will swear to their grave and back that should be
> done by factoring out the tests into a list and iterating over it, and
> NO OTHER WAY WHATSOEVER, but I don't buy it.  That's a lot of
> boilerplate--the very thing Python is normally so good at minimizing--
> when it might not be needed.  It would be the right thing for a
> complex, pluggable, customizable input filter; but is rarely a better
> solution for a simple text processing script.

I'll swear to my grave that there is always a better way than a lot of 
nested regex conditions, and that may or may not involve a list but 
there are plenty of other ways. That's why this is such a hard question 
to answer definitively: every situatiuon has a different answer.

> 
> Quick, at a glance, which code snippet will you understand faster
> (pretend you know Perl):
> 
> 
> if (/name=(.*)/) {
>     $name = chop(\1);
> } elsif (/id=(.*)/) {
>     $id = chop(\1);
> } elsif (/phone=(.*)/) {
>     $phone = chop(\1);
> }

I get a headache with that: somehow I have to either magically know 
which variable out of name, id and phone exists or I have to set all 3 
variables with suitable defaults for the unset ones. Perl I believe will 
allow access to unset variables but Python doesn't, so it looks like 
I'll have a bunch of extra code to make sure they all get set.

> 
> 
> vs.
> 

PATTERN = re.compile('(?:name=(.*))|(?:id=(.*))|(?:phone=(.*))')
...
m = PATTERN.match(argument)
if not m:
   raise FormatError('bad input: %s' % argument)
name, id, phone = m.groups()

oops, not so much extra code to set them after all. Actually in practice 
I'd probably use something more like:

PATTERN = re.compile('''(?:name=(?P<name>.*))
    |(?:id=(?P<id>.*))
    |(?:phone=(?P<phone>.*))''', re.VERBOSE)
...
m = PATTERN.match(argument)
if not m:
   raise FormatError('bad input: %s' % argument)
values = m.groupdict()

as I find named groups much less error prone.



More information about the Python-list mailing list