If/then style question
Ethan Furman
ethan at stoneleaf.us
Thu Dec 16 17:11:51 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.
As far as if/else goes, I prefer the second style also.
As far as returning bad codes, you are better off raising exceptions:
def myMethod(self, arg1, arg2):
if some_bad_condition:
raise Bad1()
elif some_other_bad_condition:
raise Bad2()
elif yet_another_bad_condition:
raise Bad3()
do_some_useful_stuff
# no need to return 'good' code -- success means no problems
~Ethan~
More information about the Python-list
mailing list