Last active
May 27, 2016 10:51
-
-
Save BruceZhang1993/2200730799fcff7e7ae1 to your computer and use it in GitHub Desktop.
Python Tail Call Optimize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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