Top level of a recursive function
Chris Angelico
rosuav at gmail.com
Tue Dec 13 13:06:04 EST 2022
On Wed, 14 Dec 2022 at 05:01, Mats Wichmann <mats at wichmann.us> wrote:
>
> On 12/13/22 10:36, Chris Angelico wrote:
> > On Wed, 14 Dec 2022 at 03:35, Michael F. Stemper
> > <michael.stemper at gmail.com> wrote:
> >>
> >> 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?
> >>
> >
> > Why does it have to be the same function?
> >
> > def _sort_recursive(stuff, keys, start, end):
> > """imagine a nice implementation of some sorting algorithm here"""
> >
> > def sort(stuff, key=None):
> > if key:
> > keys = [key(x) for x in stuff]
> > else:
> > keys = stuff
> > return _sort_recursive(stuff, 0, len(stuff))
>
> if some support for this position is needed, this is roughly how the
> stdlib glob() function is implemented.
>
Yeah, lots of things are done that way. You'll find a variety of
naming conventions around different languages and libraries, including
"_low_FUNCTIONNAME" or "_internal_FUNCTIONNAME" etc. It's definitely
easier than trying to mess with tracking toplevel status.
ChrisA
More information about the Python-list
mailing list