How to do this in Python...

Stefan Schwarzer sschwarzer at sschwarzer.net
Sat Jan 25 16:14:17 EST 2003


Peter Hansen wrote:
> Michael Tiller wrote:
>> 
>> I want to be clear about something.  I have no particular fondness for
>> the...
>> if (a=b) then ...
>> "feature" in C.  > My main problem is that I wanted to do involved mutually
>> exclusive cases, e.g.,
>> 
>> if (match=re.match(pattern1,string)):
>>   // Hey I found something that matches pattern1
>> elif (match=re.match(pattern2,string)):
>>   // This matches pattern2
>> elif (match=re.match(pattern3,string)):
>>   // This matches pattern3
>> else:
>>   // I didn't find a match
>> 
>> Now for those who think that the above code is "obfuscated", I would argue
>> that this is far worse:
> [snip ugly non-Pythonic alternative]
> 
> There are probably "better" ways of approaching this in Python than trying
> to structure it with a large series of if/elif's, even if Python had the
> construct you were seeking.  The approach I would choose would probably be 
> to put the various patterns in a nice list of tuples along with function 
> references which actually implement the code I need, then iterate over it
> with a simple for loop, calling the function corresponding to whichever
> pattern first matches.

So we could get something like

potential_patterns = (pattern1, pattern2, pattern3)
for pattern in potential_patterns:
     match = re.match(pattern, string)
     if match is not None:
         # found it, do something, then ...
         break
else:
     # didn't find it (if you need this branch at all)

That's reasonable, I think, especially if you have a lot of patterns to test
against. The loop seems not as redundant as the if/elif/else chain above.

Oh-I-found-a-use-for-for-else-ly yours
  Stefan





More information about the Python-list mailing list