New tail recursion decorator
Michele Simionato
michele.simionato at gmail.com
Wed May 10 10:45:25 EDT 2006
Kay Schluehr wrote:
> for all those who already copied and pasted the original solution and
> played with it I apologize for radical changes in the latest version (
> the recipe is on version 1.5 now ! ). The latest implementation is
> again a lot faster than the previous one. It does not only get rid of
> exceptions but also of stack-frame inspection.
This is spectacular!!
I would rewrite it as follows:
CONTINUE = object() # sentinel value returned by iterfunc
def tail_recursive(func):
"""
tail_recursive decorator based on Kay Schluehr's recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
"""
var = dict(in_loop=False, cont=True, argkw='will be set later')
# the dictionary is needed since Python closures are read-only
def iterfunc(*args, **kwd):
var["cont"] = not var["cont"]
if not var["in_loop"]: # start looping
var["in_loop"] = True
while True:
res = func(*args,**kwd)
if res is CONTINUE:
args, kwd = var["argkw"]
else:
var["in_loop"] = False
return res
else:
if var["cont"]:
var["argkw"] = args, kwd
return CONTINUE
else:
return func(*args,**kwd)
return iterfunc
Using my decorator module 'tail_recursive' can even be turned in a
signature-preserving
decorator. I think I will add this great example to the documentation
of the next version
of decorator.py!
Michele Simionato
More information about the Python-list
mailing list