Skip to content

Instantly share code, notes, and snippets.

@BruceZhang1993
Last active May 27, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BruceZhang1993/2200730799fcff7e7ae1 to your computer and use it in GitHub Desktop.
Save BruceZhang1993/2200730799fcff7e7ae1 to your computer and use it in GitHub Desktop.
Python Tail Call Optimize
import sys
class TailRecurseException:
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
def tail_call_optimized(g):
"""
This function decorates a function with tail call
optimization. It does this by throwing an exception
if it is it's own grandparent, and catching such
exceptions to fake the tail call optimization.
This function fails if the decorated
function recurses in a non-tail context.
"""
def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back and f.f_back.f_back.f_code == f.f_code:
raise TailRecurseException(args, kwargs)
else:
while 1:
try:
return g(*args, **kwargs)
except TailRecurseException, e:
args = e.args
kwargs = e.kwargs
func.__doc__ = g.__doc__
return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment