If/then style question
Jean-Michel Pichavant
jeanmichel at sequans.com
Fri Dec 17 08:22:35 EST 2010
John Gordon wrote:
> (This is mostly a style question, and perhaps one that has already been
> discussed elsewhere. If so, a pointer to that discussion will be
> appreciated!)
>
> When I started learning Python, I wrote a lot of methods that looked like
> this:
>
>
> def myMethod(self, arg1, arg2):
>
> if some_good_condition:
>
> if some_other_good_condition:
>
> if yet_another_good_condition:
>
> do_some_useful_stuff()
> exitCode = good1
>
> else:
> exitCode = bad3
>
> else:
> exitCode = bad2
>
> else:
> exitCode = bad1
>
> return exitCode
>
>
> 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
>
> I like this style more, mostly because it eliminates a lot of indentation.
>
> However I recall one of my college CS courses stating that "one entry,
> one exit" was a good way to write code, and this style has lots of exits.
>
> Are there any concrete advantages of one style over the other?
>
> Thanks.
>
>
What about,
def myMethod():
for condition, exitCode in [
(cond1, 'error1'),
(cond2, 'very bad error'),
]:
if not condition:
break
else:
do_some_usefull_stuff() # executed only if the we never hit the
break statement.
exitCode = good1
return exitCode
This version uses the 'for ... else' statement. You can easily add
conditions by simply adding a line in the list, that's it.
Note that this code uses a shadow declaration of exitCode in the for
loop. If you're not comfortable with that, you'll have to use a properly
'declared' variable retCode and write retCode = exitCode before
breaking. Actually I would advise to do so.
JM
More information about the Python-list
mailing list