New tail recursion decorator
Carl Banks
invalidemail at aerojockey.com
Thu May 11 00:00:59 EDT 2006
Michele Simionato wrote:
> 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
CONTINUE could be put inside tail_recursive, couldn't it? And to
squeeze a little more speed out of it, var could be a list (saves a
hash lookup).
Cool decorator.
Carl Banks
More information about the Python-list
mailing list