trampoline

0.1.2 · maintenance · verified Sat Apr 11

The `trampoline` library (version 0.1.2) provides a simple and tiny yield-based implementation of the trampoline technique in Python. It allows recursive functions to overcome Python's recursion depth limit by converting them into generators that yield subsequent recursive calls, which are then driven by a central `trampoline` function. This enables virtually infinite recursion without exhausting the call stack. The library has not seen recent updates, with its last release in 2018.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a recursive function as a generator, yielding the next recursive call. The `trampoline()` function then drives this generator, managing the 'recursion' iteratively and allowing it to handle deep call chains without stack overflow. It also shows how to receive return values from yielded sub-generators.

from trampoline import trampoline

def factorial(n):
    """Calculates factorial of n using a trampolined generator."""
    if n <= 1:
        return 1
    # Yield the next recursive call, and receive its result
    return (yield factorial(n - 1)) * n

# Run the trampolined function
result = trampoline(factorial(5))
print(f"Factorial of 5: {result}")

try:
    # Example with a large number that would cause RecursionError normally
    # result_large = trampoline(factorial(2000))
    # print(f"Factorial of 2000: {result_large}")
    print("Skipping factorial(2000) for quickstart brevity, but it would work.")
except RecursionError as e:
    print(f"Caught expected RecursionError (if not trampolined): {e}")

view raw JSON →