No more `RecursionError: maximum recursion depth exceeded`
Project description
precursion

precursion – Python module to avoid RecursionError: maximum recursion depth exceeded easily
Usage
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
print(sumrange(1000))
# RecursionError: maximum recursion depth exceeded
Let's fix it with precursion module:
@precurse
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:
Pros
The code looks cleaner. Yep.
Cons
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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
precursion-1.0.0.tar.gz
(2.4 kB
view details)
File details
Details for the file precursion-1.0.0.tar.gz.
File metadata
- Download URL: precursion-1.0.0.tar.gz
- Upload date:
- Size: 2.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ba750d0f63ef9820abc40bd0ac2384d3c23eca656d4880ac4af8a22b1d467a86
|
|
| MD5 |
f4e38c01694b8816dc1123d92a2ee655
|
|
| BLAKE2b-256 |
5d22a252602a16ca6db0b4c31a155ca4ad9b765960b69853070581859091add2
|