Self function

Arnaud Delobelle arnodel at googlemail.com
Mon May 4 14:51:03 EDT 2009


bearophileHUGS at lycos.com writes:

> Steve Howell:
>>two methods with almost identical names, where one function is the
>>public interface and then another method that does most of the
>>recursion.<
>
> Thanks Guido & Walter both Python and D support nested functions, so
> in such situations I put the recursive function inside the "public
> interface" function/method.

Yes, this is a common idiom for me:

def public_function(a, b):
    def rec():
        ...
    return rec()

E.g, to continue with the factorial toy example (of course for this
particular example and in this particular language, a loop would be more
appropriate):

def fac(n):
    def rec(n, acc):
        if n <= 1:
            return acc
        else:
            return rec(n - 1, n*acc)
    return rec(n, 1)

This is tail recursive, but Python does not optimise tail-calls so there
is not much point.

> Recursion is a high-level way to represent certain kinds of algorithms
> in a short and readable way (when data structures are nested, the most
> natural algorithms that work on them are recursive). But in Python
> function calls are slow, the maximum level of nested calls is limited
> (and it can't grow too much), so this has sometimes forced me to
> manually convert recursive functions into iterative ones with a stack.
> This is silly for a supposed high-level language. The bad support for
> recursivity is one of the few faults of Python.

Bearophile, there is a thread on python-ideas about tail-call
optimization at the moment.

-- 
Arnaud



More information about the Python-list mailing list