Cascading ifs

irstas at gmail.com irstas at gmail.com
Mon Apr 2 17:09:28 CEST 2007


On Apr 2, 4:20 pm, Ernesto García García
<titogarcia_nospamplea... 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


You might be able to use "guard clauses":
http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html


match = my_regex.search(line)
if match:
   doSomething(line)
   return

match = my_regex2.search(line)
if match:
   doSomething2(line)
   return


But if all of the blocks contain the same code like they do in your
example, you're better off using the solutions provided by Wojciech
Muła and Duncan Booth, because they abstract away the repetition.




More information about the Python-list mailing list