https://github.com/python273/precursion
No more `RecursionError: maximum recursion depth exceeded`
https://github.com/python273/precursion
module python recursion
Last synced: 4 days ago
JSON representation
No more `RecursionError: maximum recursion depth exceeded`
- Host: GitHub
- URL: https://github.com/python273/precursion
- Owner: python273
- License: mit
- Archived: true
- Created: 2018-06-14T18:11:44.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-06-15T06:26:25.000Z (over 7 years ago)
- Last Synced: 2025-09-22T19:09:59.904Z (4 months ago)
- Topics: module, python, recursion
- Language: Python
- Homepage:
- Size: 4.88 KB
- Stars: 10
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
precursion [](https://pypi.org/project/precursion/) 
======
**precursion** – Python module to avoid `RecursionError: maximum recursion depth exceeded` easily
## Usage
Ok, let's write some recursive function:
```python
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 pass a large number as the argument
```python
print(sumrange(1000))
# RecursionError: maximum recursion depth exceeded
```
Let's fix it with precursion module:
```python
from precursion import precurse
@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 the unwrapped function, so you `yield` an unwrapped generator
## Pros and cons:
#### Pros
The code looks cleaner. Yep.
#### Cons
Function calls have performance and memory overhead, so using
this decorator is slower than if you replace recursive calls with
a stack with a while-loop or
a [tail recursive call](https://en.wikipedia.org/wiki/Tail_call) with
a while-loop.