A goto-like usage of a function

Peter Hansen peter at engcorp.com
Thu Jul 29 19:09:59 CEST 2004


Bart Nessux wrote:

> I understand recursion to be a loop or a loop to be recursion... however 
> you prefer to look at it. 

Absolutely not.  Recursion is more like a spiral, rapidly closing
in on itself until you're trapped in the middle, or maybe a
swirling whirlpool that will sink your program over time...

Just because you can use recursion to implement something that
appears to loop doesn't mean it's a good idea.  Much better
to get out of that frame of mind...  Recursion does _not_ get
you back to where you were, as a real loop would.

The key is to understand that each time you call a function,
more data is put on the "stack", which has a finite size.
Basically the context of the calling function is preserved
when you call a subroutine, including all the local variables,
plus the "return address" so the interpreter knows where to
go back to.

Whether you do it through recursion or some other means,
if you get too deeply nested you will crash, and even if you
don't you still have the overhead of "unwinding" all those
stack frames when you finally return.  It may look like
it falls off the end of the function, but in fact it is
actually returning to the previous stack frame, in the place
just after where the function call was, then it returns from
there to the previous stack frame, then returns to the previous
one, each time popping a frame off the stack, all the way up
to the top of the stack.

While it might be okay for a trivial script that is just asking
for user input, it is terribly bad style and you would do well
to learn to do it differently.

All IMHO, and theoretical discussions of tail recursion
notwithstanding.

-Peter



More information about the Python-list mailing list