@call_once python macro for unlimited recursion depth
dev.to·22h·
Discuss: DEV
Flag this post

I like competitive programming (like Meta Hacker Cup). Where you solve algorithmic puzzles in limited time. In many problems, a recursive solution feels more natural than an iterative one — but Python’s recursion depth limit (usually around 1000) makes it impractical for larger inputs.

So I built a small macro — @call_once — that lets you write recursive functions with virtually unlimited recursion depth.

Example

Let’s take a simple Fibonacci example:

def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)

print(fib(200_000) % 1_000)

This will crash immediately — Python’s call stack can’t handle that depth.

But with one decorator:

@call_once
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n -...

Similar Posts

Loading similar posts...