Skip to content

Instantly share code, notes, and snippets.

@shotahorii
Created January 9, 2014 06:40
Show Gist options
  • Save shotahorii/8330320 to your computer and use it in GitHub Desktop.
Save shotahorii/8330320 to your computer and use it in GitHub Desktop.
Tail Recursive

A Decorator class for Tail Recursive Optimisation.
Written by George Sakkis here.

class tail_recursive(object):
def __init__(self, func):
self.func = func
self.firstcall = True
self.CONTINUE = object()
def __call__(self, *args, **kwd):
if self.firstcall:
func = self.func
CONTINUE = self.CONTINUE
self.firstcall = False
try:
while True:
result = func(*args, **kwd)
if result is CONTINUE: # update arguments
args, kwd = self.argskwd
else: # last call
return result
finally:
self.firstcall = True
else: # return the arguments of the tail call
self.argskwd = args, kwd
return self.CONTINUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment