"return" in def
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Tue Dec 30 02:00:59 CET 2008
On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote:
> One style of coding I heard about once only permits returns at the end
> of a function. It claims it makes it easier to see the function as a
> mathematical object.
That's silly. You treat the function as a black box: input comes in, and
output comes out. You have no idea of what happens inside the black box:
it could loop a thousand times, take 150 different branches, or take one
of 37 different exit points. From the outside, it's still exactly like a
mathematical object. Internal complexity is irrelevant. This is why
mathematicians can perform algebra on complicated functions like Bessel's
function (of the first or second kind), without needing to care that
actually calculating Bessel's function is quite tricky.
What I think the one-return-per-function style is aiming at is that it is
(sometimes) easier to analyse the internals of the function if there are
few branches. The more complicated branches you have, the harder it is to
analyse the function. Early exits on their own are not the cause of the
complexity: it's the number of branches leading to the early exit that
causes the problem.
Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti
code. 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.
It introduces an extra variable "found_item" and two extra if blocks. I
don't think the claim that the version with an early exit is more
complicated than the version without can justified.
--
Steven
More information about the Python-list
mailing list