Top level of a recursive function

Mats Wichmann mats at wichmann.us
Tue Dec 13 12:57:59 EST 2022


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.



More information about the Python-list mailing list