On Wed, 14 Dec 2022 at 03:35, Michael F. Stemper
<michael.stem...@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))

With purely recursive functions (where every call to the function
truly could have been a top-level call - a lot of mathematical
functions work out this way), it makes sense to call the
externally-callable function recursively; but for anything more messy,
it's usually easiest to make the recursive part internal, and then
have a top-level function that calls into the recursive one.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to