[Python-ideas] return from (was Re: Tail recursion elimination)
Terry Reedy
tjreedy at udel.edu
Mon Jan 20 02:58:17 CET 2014
On 1/19/2014 8:15 PM, David Mertz wrote:
> On Sun, Jan 19, 2014 at 3:13 PM, Terry Reedy
> Proposal (mostly not mine): add 'return from f(args)', in analogy
> with 'yield from iterator', to return a value to the caller from an
> execution frame running f(args) (and either reuse or delete the
> frame that ran 'return from'). The function name 'f' would not have
> to match the name of the function being compiled, this would
> actually be TCO, even if it were nearly always used for recursive
> tail calls. That does mean that is would work for mutually tail
> recursive functions.
> I was mostly disliking the idea of TCO during this discussion. However,
> the idiom of 'return from' seems sufficiently elegant and explicit--and
> has exactly the semantics you'd expect from 'yield from'--that I am
> actually +1 on that idea.
>
> Being an explicit construct, it definitely becomes a case of "consenting
> adults" not of implicit magic. I.e. you are declaring right in the code
> that you don't expect to see a frame in a stack trace, which is fair
> enough. I mean, if you *really* wanted to you could muck around with
> 'sys._getframe(N).f_whatever' already which would give inaccurate
> tracebacks too. Probably there would be a way to removed frames from
> the stack even, using some such trick in current python.
Acting upon encountering a call-return bytecode pair has the following
problems.
1. It is CPython specific and probably not portable to all
implementations. Guido has cited this as a major block.
2. It must by optional, but how?
2A. A command line option is too broad. For some inputs, functions would
return or crash depending on the option. Not good. Also, command line
options do not work well when starting Python with icons.
2B. A future import would have a narrower scope but still might be too
broad. It would also be an abuse because the 'future' would be a fake
future that is partly now and partly never.
2C. A sys flag has the non-icon problems of a command line option.
An explicit indicator in the function avoids most of these problems. The
only one I am not sure about is other implementations, but with explicit
system independent syntax, there is at least a chance.
A developer can temporarily switch back to return (with small enough
input) to get a full stack trace for exactly one function, just as one
can temporarily add 'print' to get a 'loop trace' for exactly one loop.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list