If/then style question

alex23 wuwei23 at gmail.com
Thu Dec 16 19:18:07 EST 2010


John Gordon <gor... at panix.com> wrote:
> But lately I've been preferring this style:
>
>   def myMethod(self, arg1, arg2):
>
>     if some_bad_condition:
>       return bad1
>
>     elif some_other_bad_condition:
>       return bad2
>
>     elif yet_another_bad_condition:
>       return bad3
>
>     do_some_useful_stuff()
>     return good1

For more than 2 tests in a function like this, I'd probably use
dictionary dispatch:

def myMethod(self, arg1, arg2):
    branches = dict(
        cond1:  bad1,
        cond2:  bad2,
        cond3:  bad3
    )

    cond = <expression>

    if cond == cond_good:
        do_some_useful_stuff()
        exitCode = good1
    else:
        exitCode = branches[cond]

    return exitCode



More information about the Python-list mailing list