Possibly Pythonic Tail Call Optimization (TCO/TRE)

Chris Angelico rosuav at gmail.com
Mon Jul 13 07:47:07 EDT 2015


On Mon, Jul 13, 2015 at 9:22 PM, Jussi Piitulainen
<jpiitula at ling.helsinki.fi> wrote:
> That's oddly restricted to self-calls. To get the real thing, "recur"
> should replace "return" - I'm tempted to spell it "recurn" - so the
> definition would look like this:
>
> def factorial(n, acc=1):
>    if n == 0:
>       return acc
>    else:
>       recur factorial(n-1, acc=(acc*n))
>
> Probably it would still be syntactically restricted to calls

Huh. Now it looks like the 'exec' operation (the C function and shell
operation, not the Python keyword/function) - it's saying "replace the
current stack frame with _this_", which looks reasonable. It doesn't
have to be recursion. The thing is, you would have to use this ONLY
when you don't care about the current stack frame; so you could do a
logging decorator thus:

def log_calls(func):
    @functools.wraps(func)
    def wrapped(*a, **kw):
        logging.debug("Calling %s(%r, %r)", func.__name__, a, kw)
        recur func, a, kw
    return wrapped

When an exception occurs inside the wrapped function, the wrapper
won't be visible - but that's not a problem, because it doesn't affect
anything. Like every other tool, it would be something that could
easily be abused, but this actually does justify the removal.

It would almost certainly need to be language syntax. I've done it up
as a keyword that takes "function, args, kwargs" rather than a prefix
on a function call, which emphasizes that the part after it is NOT an
expression. In a sense, it makes a counterpart to lambda - where
lambda takes an expression and turns it into a function, recur takes a
function and treats it as if its body were part of the current
function. Kinda.

Does that make sense to anyone else?

ChrisA



More information about the Python-list mailing list