Tacopy Tail-Call Optimization for Python Tacopy is a Python library that provides a decorator to optimize tail-recursive functions by transforming them into iterative loops. This eliminates the risk of stack overflow errors for deep recursion. Features Automatic Tail-Call Optimization : Transforms tail-recursive functions into efficient loops : Transforms tail-recursive functions into efficient loops Stack Overflow Prevention : Handle arbitrarily deep recursion without hitting Python's recursion limit : Handle arbitrarily deep recursion without hitting Python's recursion limit Significant Performance Gains : 1.41x-2.88x faster than regular recursion (see benchmarks) : than regular recursion (see benchmarks) Validation : Ensures functions are properly tail-recursive before transformation : Ensures functions are properly tail-recursive before transformation No Runtime Overhead : Optimization happens once at decoration time : Optimization happens once at decoration time Preservation of Function Metadata: Keeps docstrings, type hints, and other metadata intact Installation # Using uv (recommended for development) uv add tacopy-optimization # Using pip pip install tacopy-optimization Quick Start from tacopy import tacopy @ tacopy def factorial_mod_k ( acc : int , n : int , k : int ) -> int : """Calculate (acc * n!) mod k using tail recursion.""" if n == 0 : return acc % k return factorial_mod_k ( acc * n % k , n - 1 , k ) # This would normally cause a stack overflow, but works with @tacopy result = factorial_mod_k ( 1 , 1_000_000 , 79 ) print ( result ) # Output: 0 How It Works Tacopy uses AST (Abstract Syntax Tree) transformation to convert tail-recursive functions into iterative loops. For example: Original function: @ tacopy def factorial ( n : int , acc : int = 1 ) -> int : if n == 0 : return acc return factorial ( n - 1 , acc * n ) Transformed to (conceptually): def factorial ( n : int , acc : int = 1 ) -> int : _n = n _acc = acc while True : if _n == 0 : return _ac...
First seen: 2025-12-05 07:15
Last seen: 2025-12-05 18:17