"return" in def

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

Steven D'Aprano a écrit :
(snip)
Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti
code.

Mostly, yes. It can also be a way to help avoiding "resource leaks"
(memory or whatever) - just like try/finally blocks or the 'with'
statement in Python.
But used wisely, early exists can simplify, not complicate, code.

Consider the following:

def find_ham(alist):
for item in alist:
if isinstance(item, Ham):
return item
raise ValueError('no ham found')


def find_spam(alist):
found_item = None
for item in alist:
if found_item is not None:
if isinstance(item, Spam):
found_item = item
if found_item is None:
raise ValueError('no spam found')
else:
return found_item
The second version has double the number of lines of code of the first.

And doesn't do the same thing (hint: you forgot a break statement). Also
and FWIW, the "single exit" golden rule (hem) comes from languages
without exception handling. So a fair comparison would be:

def find_egg(alist):
for item in alist:
if isinstance(item, Egg):
return item
return None

vs:

def find_sausage(alist):
found = None
for item in alist:
if isinstance(item, Sausage):
found = item
break
return found

Granted, this still doesn't make the second version better than the
first !-)

But:
I don't think the claim that the version with an early exit is more
complicated than the version without can justified.

Certainly not in this simple (simplistic ?) example. Now in C or Pascal,
functions tend to be much longer and complicated, thanks to all the gory
details one has to take care of.

Not that I'm advocating "no early return" as a "golden rule" - specially
in Python where functions tend to be short and readable -, but there
really are cases (depending on the language *and* concrete use case)
where avoiding early returns makes for more readable and robust code.

My 2 cents...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top