Skip to main content

No more `RecursionError: maximum recursion depth exceeded`

Project description

precursion PyPI Python 2.7, 3.4, 3.5, 3.6

precursion – Python module to avoid RecursionError: maximum recursion depth exceeded easily


Ok, let's write recursive function:

def sumrange(x):
    if x == 0:
        return 0

    r = sumrange(x - 1)
    return x + r

print(sumrange(10)  # 55

Pretty simple. But what if we call it with bigger argument

# RecursionError: maximum recursion depth exceeded

Let's fix it with precursion module:

def sumrange(x):
    if x == 0:
        # return was:
        # return 0
        # now we need to use StopIteration exception:
        raise StopIteration(0)

    # recursive call was:
    # r = sumrange(x - 1)
    # now we use yield:
    r = yield sumrange.r(x - 1)
    raise StopIteration(x + r)

print(sumrange(1000))  # 500500!!1

That's it!

What is .r in sumrange.r?

It's unwrapped function, so you yield unwrapped generator

Pros and cons:


The code looks cleaner. Yep.


Function calls have performance and memory overhead, so using the decorator is slower than if you use Tail-call optimization via while or implement a stack inside a function.

Release history Release notifications

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
precursion-1.0.0.tar.gz (2.4 kB) Copy SHA256 hash SHA256 Source None

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page