[Python-Dev] Explicit Tail Calls
rhamph at gmail.com
Fri Oct 12 20:09:40 CEST 2007
On 10/12/07, Shane Hathaway <shane at hathawaymix.org> wrote:
> I'm interested in seeing a good way to write tail calls in Python. Some
> algorithms are more readable when expressed using tail recursion.
> I know tail call optimization has been discussed before , but I would
> like to consider a different approach. The previous discussion centered
> on implicit tail call optimization, which incurs the risk of changing
> the behavior of currently working code. (For example, is it safe to
> optimize tail calls within try...finally blocks? Probably not. And I
> generally want all stack frames to appear in tracebacks, unless I say
> I would like to suggest an explicit form of tail calls. A new built-in
> exception type called "Return" will be added, and it will be used like this:
So long as you're willing to make it explicit (which I strongly
encourage), you can accomplish nearly anything you'd like with
decorators and functions. There doesn't seem to be strong enough use
cases to get anything into the core language anyway.
If you don't like the existing decorator recipes I can help you come
up with a better one in private, off the list.
> def fact2(n, v):
> if n:
> raise Return(fact2, n-1, v*n)
> return v
I hope your use cases are better than this. ;)
> The interpreter will catch Return exceptions and use them to call
> something else. The caller of a function that uses "raise Return" will
> see the result of the tail call as the returned value, rather than the
> Return exception. I am not yet considering implementation details.
> Not all algorithms are good candidates for this. I used the fact2
> example only because it's readily available. I know there are other
> people interested in tail call optimization in Python  ; perhaps
> some of them are watching and can provide better examples.
> Furthermore, there might be some explicit syntax that converts "return
> f(...)" statements to "raise Return(f, ...)", such as a decorator.
> However, I'm less interested in the syntax and more interested in the
> basic capability.
>  http://mail.python.org/pipermail/python-dev/2004-July/046150.html
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474088
>  http://www.voidspace.org.uk/python/weblog/arch_d7_2007_09_22.shtml#e833
> Python-Dev mailing list
> Python-Dev at python.org
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/rhamph%40gmail.com
Adam Olsen, aka Rhamphoryncus
More information about the Python-Dev