How to do this in Python...
Peter Hansen
peter at engcorp.com
Fri Jan 24 17:36:32 EST 2003
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. Anything complex enough to need a structure like
the above, in my opinion, needs to have the subordinate code blocks ripped
out to separate functions, just for maintainability. Maybe that's just me
though...
-Peter
More information about the Python-list
mailing list