My tail call optimizing decorator

M

Miguel Perez

Please critique this tail call optimizing decorator I've written. I've
tried to fix the pitfalls of other proposed decorators, and the result
is this one that supports mutual recursion, does not use exceptions,
stack inspection or any implementation-dependent hack, and is pretty
short and fast - the fastest out of the ones I could find and try. In
fact, in tail-recursive environments I tested the impact of using the
decorator is difficult to even measure, as the extra time the
decorator takes to run is probably saved by the better use of cache
memory. The only caveat is that if used in a function that's not
called in a tail-recursive fashion, bad things will happen.

def tailcall(f):
'''Decorator that implements tail call optimization.

Supports cooperative tail call - even when only one of the functions
is
decorated, and all exceptions pass through it. You can tell the
functions
that have been tail optimized because they have "tco" before them in
the
stack frame.

The only caveat is that if you attempt to decorate a function that
isn't
called in a tail recursive fashion from another decorated function,
you'll
get wrong results.'''
tdata = [False] #[Optimizing?]
DO_CALL = object() #Call marker
def tco(*a, **aa):
if tdata[0]:
return DO_CALL, a, aa
else:
tdata[0] = True
ret = f(*a, **aa)
while type(ret) is tuple and ret and ret[0] is DO_CALL:
ret = f(*ret[1], **ret[2])
tdata[0] = False
return ret
tco.__doc__ = f.__doc__
return tco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top