[Python-ideas] A Continuations Compromise in Python
Joel Bender
jjb5 at cornell.edu
Mon May 4 22:48:08 CEST 2009
Adam Olsen wrote:
> def a():
> return b
>
> def b():
> return a
>
> def trampoline(func):
> while True:
> func = func()
Every once in a while (usually with actor and message passing
algorithms) I get the urge to have something like this, I didn't realize
it had a formal name:
def a(n):
trampoline b(n-1)
print "never gets printed"
def b(n):
if cond(n):
return n
else:
trampoline a(n * 2)
print "never gets printed"
So a trampolined call bails out of the current call frame, and whatever
the trampolined call returns, it returns.
>>> a(5) == b(4)
True
>>>
The same thing would happen with generators and try/except handlers:
def a(n):
try:
yield n
trampoline b(n-1)
except Exception, err:
print "a() error:", err
def b(n):
yield n
raise RuntimeError, "snort"
>>> for i in a(2):
... print i
...
2
1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in b
RuntimeError: snort
>>>
Joel
More information about the Python-ideas
mailing list