Cascading ifs

Duncan Booth duncan.booth at invalid.invalid
Mon Apr 2 09:40:45 EDT 2007


Ernesto García García <titogarcia_nospamplease_ at gmail.com> wrote:

> Hi experts,
> 
> How would you do this without the more and more indenting cascade of
> ifs?: 
> 
> match = my_regex.search(line)
> if match:
>    doSomething(line)
> else:
>    match = my_regex2.search(line)
>    if match:
>      doSomething2(line)
>    else:
>      match = my_regex3.search(line)
>      if match:
>        doSomething3(line)
> 
> etc.
> 
> Thanks in advance and regards,
> Ernesto
> 

PATTERNS = [
   (my_regex, doSomething),
   (my_regex2, doSomething2),
   (my_regex3, doSomething3),
]
...

for regex, action in PATTERNS:
    match = regex.search(line)
    if match:
        action(line)
        break


Also be aware that repeatedly calling the search method with different 
regular expressions is horribly inefficient. You would be much better to 
combine the regular expressions into one and check which groups match 
(although admittedly that behaves differently since it would find the 
regex which matches earliest in the string instead of finding the first 
regex which matches anywhere).



More information about the Python-list mailing list