Top level of a recursive function

Michael F. Stemper michael.stemper at gmail.com
Tue Dec 13 09:46:29 EST 2022


It's easy enough -- in fact necessary -- to handle the bottom
level of a function differently than the levels above it. What
about the case where you want to handle something differently
in the top level than in lower levels? Is there any way to tell
from within a function that it wasn't invoked by itself?

I've come up with a hack to support different processing, by
use of an extra argument, as shown in this simplified example:

def fred(cf,toplevel=True):
   x = cf[0]
   if len(cf)>1:
     if toplevel:
       return x + fred(cf[1:],False)
     else:
       return "(" + x + fred(cf[1:],False) + ")"
   else:
     if toplevel:
       return x
     else:
       return "(" + x + ")"

Aside from being ugly, this lets the caller diddle with "toplevel",
which shouldn't really be externally modifiable.

Are there better ways to do this?
-- 
Michael F. Stemper
I refuse to believe that a corporation is a person until Texas executes one.


More information about the Python-list mailing list