Skip to content

Instantly share code, notes, and snippets.

@ChrisPenner
Last active September 19, 2020 08:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ChrisPenner/c958afbf6e7a763c188d8b83275751bb to your computer and use it in GitHub Desktop.
Save ChrisPenner/c958afbf6e7a763c188d8b83275751bb to your computer and use it in GitHub Desktop.
Tail Recursion in Python without Introspection
from tail_recursion import tail_recursive, recurse
# Normal recursion depth maxes out at 980, this one works indefinitely
@tail_recursive
def factorial(n, accumulator=1):
if n == 0:
return accumulator
recurse(n-1, accumulator=accumulator*n)
class Recurse(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def recurse(*args, **kwargs):
raise Recurse(*args, **kwargs)
def tail_recursive(f):
def decorated(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except Recurse as r:
args = r.args
kwargs = r.kwargs
continue
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment