This question already has an answer here:
I'm trying to sort out whether this is just a personal preference thing or whether it's actually bad practice to do this one way or another. I did try to reference PEP8 first, and I did not see an answer.
What I'm talking about here is the use of more than one
return statement. In these examples, it's not such a big deal, as they are very short and easily read.
def foo(obj): if obj.condition: return True return False def bar(obj): answer = False if obj.condition: answer = True return answer
It bugs me to assign a variable every time
bar() is called, instead of just determining the answer and returning it. But in a longer function a second
return might be hidden and so someone reading the code may have not realized that the function might return a value before hitting the end of the line:
def spam(obj): blurb = "Francis" if obj.condition: blurb = map(gormf, [z for z in porp(obj)]) return blurb elif not obj.condition and dreg(obj.jek): blurb = obj.hats * 17 if blurb % 13: return blurb else: blurb = obj.name return "Whales and %s" blurb
That's a terrible function, but I think you see what I'm poking at.
So is it preferable to create a function to have a single, clear exit - even if it's a few more operations than you actually need? Or should one try to root this out whenever possible in favor of shorter code?