Skip to content

Instantly share code, notes, and snippets.

@r14c
Created December 2, 2014 22:14
Show Gist options
  • Save r14c/1350861c19bae9156de6 to your computer and use it in GitHub Desktop.
Save r14c/1350861c19bae9156de6 to your computer and use it in GitHub Desktop.
Tail Recursion Decorator
# -*- coding: utf-8 -*-
class tail_recursive(object):
"""
Based on comments on this active state recipe: <http://code.activestate.com/recipes/496691/>
"""
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