Ошибка maximum recursion depth exceeded while calling a python object

I’ve built a crawler that had to run on about 5M pages (by increasing the url ID) and then parses the pages which contain the info’ I need.

after using an algorithm which run on the urls (200K) and saved the good and bad results I found that the I’m wasting a lot of time. I could see that there are a a few returning subtrahends which I can use to check the next valid url.

you can see the subtrahends quite fast (a little ex’ of the few first «good IDs») —

510000011 # +8
510000029 # +18
510000037 # +8
510000045 # +8
510000052 # +7
510000060 # +8
510000078 # +18
510000086 # +8
510000094 # +8
510000102 # +8
510000110 # etc'
510000128
510000136
510000144
510000151
510000169
510000177
510000185
510000193
510000201

after crawling about 200K urls which gave me only 14K good results I knew I was wasting my time and need to optimize it, so I run some statistics and built a function that will check the urls while increasing the id with 818178 (top returning subtrahends ) etc’.

this is the function —

def checkNextID(ID):
    global numOfRuns, curRes, lastResult
    while ID < lastResult:
        try:
            numOfRuns += 1
            if numOfRuns % 10 == 0:
                time.sleep(3) # sleep every 10 iterations
            if isValid(ID + 8):
                parseHTML(curRes)
                checkNextID(ID + 8)
                return 0
            if isValid(ID + 18):
                parseHTML(curRes)
                checkNextID(ID + 18)
                return 0
            if isValid(ID + 7):
                parseHTML(curRes)
                checkNextID(ID + 7)
                return 0
            if isValid(ID + 17):
                parseHTML(curRes)
                checkNextID(ID + 17)
                return 0
            if isValid(ID+6):
                parseHTML(curRes)
                checkNextID(ID + 6)
                return 0
            if isValid(ID + 16):
                parseHTML(curRes)
                checkNextID(ID + 16)
                return 0
            else:
                checkNextID(ID + 1)
                return 0
        except Exception, e:
            print "somethin went wrong: " + str(e)

what is basically does is -checkNextID(ID) is getting the first id I know that contain the data minus 8 so the first iteration will match the first «if isValid» clause (isValid(ID + 8) will return True).

lastResult is a variable which saves the last known url id, so we’ll run until numOfRuns is

isValid() is a function that gets an ID + one of the subtrahends and returns True if the url contains what I need and saves a soup object of the url to a global varibale named — ‘curRes‘, it returns False if the url doesn’t contain the data I need.

parseHTML is a function that gets the soup object (curRes), parses the data I need and then saves the data to a csv, then returns True.

if isValid() returns True, we’ll call parseHTML() and then try to check the next ID+the subtrahends (by calling checkNextID(ID + subtrahends), if none of them will return what I’m looking for I’ll increase it with 1 and check again until I’ll find the next valid url.

you can see the rest of the code here

after running the code I got about 950~ good results and suddenly an exception had raised —

«somethin went wrong: maximum recursion depth exceeded while calling a
Python object»

I could see on WireShark that the scipt stuck on id — 510009541 (I started my script with 510000003), the script tried getting the url with that ID a few times before I noticed the error and stopped it.

I was really exciting to see that I got the same results but 25x-40x times faster then my old script, with fewer HTTP requests, it’s very precise, I have missed only 1 result for 1000 good results, which is find by me, it’s impossible to rum 5M times, I had my old script running for 30 hours and got 14-15K results when my new script gave me 960~ results in 5-10 minutes.

I read about stack limitations, but there must be a solution for the algorithm I’m trying to implement in Python (I can’t go back to my old «algorithm», it will never end).

Thanks!

A Recursive function in programming is a function which calls itself. These functions find applications while constructing programs for factorial, Fibonacci series, Armstrong numbers, etc. The main idea is to break larger programs into smaller, less complex problems. With recursive functions, generating sequences becomes easy. But while using recursive functions, recursionerror may occur in python. In this article, we shall be looking into one such recursionerror: maximum recursion depth exceeded while calling a Python object

What is recursionerror?

As the name suggests, Recursionerror may occur when we are dealing with recursive functions. When we run the recursion function for a large number of times, recursion error is thrown. Python has a limit on the number of times a recursive function can call itself. This is done to ensure that the function does not execute infinitely and stops after some number of iterations. To know the recursion limit in python, we use the following code:

import sys
print(sys.getrecursionlimit())

The output is:

1000

Let us look at an example of RecursionError: maximum recursion depth exceeded. We shall take an example of a factorial function.

The following code shall generate factorial for a given number.

def find_fact(n):
  if n == 0 or n == 1:
    return 1
  else :
    return (n*find_fact(n-1))  

print("Factorial is :", find_fact(5))

Here, this program shall be executed successfully and shall print the below output:

Factorial is : 120

But if we pass a larger number into the find_fact() function, it will throw RecursionError: Maximum Recursion Depth Exceeded error.

print("Factorial is :", find_fact(5000))

Output:

RecursionError: maximum recursion depth exceeded in comparison

Since the recursion function exceeded the limit of 1000 iterations, recursionerror is thrown.

The RecursionError: Maximum Recursion Depth Exceeded error may also be thrown while we are trying to create a nested list whose length exceeds the recursion limit.

Let us take the following example. We have created a function named nested() which accepts one argument – n. Depending on the value of n, the length of that nested list would be created. Let us try to pass a value n greater than the recursion limit.

def nested(n): 
    list1 = list2 = [] 
    for i in range(n): 
        list1.append([])
        list1 = list1[0] 
    return list2

nestedlist = nested(2000)
print(nestedlist)

The output will be a recursion error.

RecursionError: maximum recursion depth exceeded while getting the repr of an object

RecursionError: Maximum Recursion Depth Exceeded While Calling A Python Object

The recursionerror for Maximum Recursion Depth Exceeded While Calling A Python Object is thrown when we are trying to call a python object in Django. The error may also occur while using Flask.

When the interpreter detects that the maximum depth for recursion has reached, it throws the recursionerror. To prevent the stack from getting overflow, python raises the recursionerror.

Best practices to avoid RecursionError: Maximum Recursion Depth Exceeded while calling a Python Object

1. Using other loops instead of recursion

To prevent the error from occurring, we can simply convert the piece of code from recursion to a loop statement.

If we take the example of the factorial function, we can convert it into a non – recursive function. We do that by placing a for loop inside the recursion function. The for loop will execute for a length equal to the value of the factorial number.

def find_fact(n):
  mul = 1
  for i in range(2,n+1):
    mul = mul * i
  return mul

print("Factorial is :", find_fact(1500))

Now, it will not throw any recursion error and simply print the large factorial number.

2. Using sys.setrecursionlimit() function

Else, if we still want to use the recursion function, we can increase the recursion limit from 1000 to a higher number. For that, we have to first import the sys library. Using the sys library, we will use the sys.setrecursionlimit() function.

import sys
sys.setrecursionlimit(2000)

Now, it will not thrown the recursionerror and the program will be executed for larger amount of recursions. On executing the recursive function, it will not throw any error and print its output.

def find_fact(n):
  if n == 0 or n == 1:
    return 1
  else :
    return (n*find_fact(n-1))  

print("Factorial is :", find_fact(1500))

3. Setting boundary conditions

It is necessary to set boundary conditions to ensures that the recursive function comes to an end. In the factorial program, the condition :

'if n == 1 or n == 0 : return 1'

is the boundary condition. It is with this condition that the loop comes to an end.

4. Creating a converging recursion

While writing the recursion condition, one has to ensure that the condition does come to an end and does not continue infinitely. The recursive calls should eventually tend towards the boundary condition.

We have to ensure that we creating a converging condition for that. In the factorial program, the ‘n*fact(n-1)’ is a converging condition that converges the value from n to 1.

5. Using Memoization

We can also use memoization to reduce the computing time of already calculated values. This way, we can speed up the calculations by remembering past calculations.

When recursive calls are made, then with memoization we can store the previously calculated values instead of unnecessarily calculating them again.


That sums up the article on RecursionError: Maximum Recursion Depth Exceeded While Calling A Python Object. If you have any questions in your mind, don’t forget to let us know in the comments below.

Until next time, Keep Learning!

  • [Solved] typeerror: unsupported format string passed to list.__format__

  • Solving ‘Remote End Closed Connection’ in Python!

  • [Fixed] io.unsupportedoperation: not Writable in Python

  • [Fixing] Invalid ISOformat Strings in Python!

In programming, recursive functions are routines or methods that call themselves directly or indirectly. Python limits the number of times a recursion function can call itself. If the recursion function exceeds that limit, Python raises the error

RecursionError: maximum recursion depth exceeded while calling a Python object

.

This tutorial will discuss the above error in detail and help you learn to debug and resolve it. We will also walk through an example to understand this error.

So let’s get started!

Recursion is a powerful technique to solve specific types of problems in programming. However, one must be very careful while dealing with recursive functions, as they may enter infinite loops.

Every recursive function has a base case that acts as a terminating condition. When a function meets the base case, it stops calling itself and returns the value back.

However, if the base case is not defined correctly or the recursive logic is incorrect, the function may end up calling itself infinitely. This means the function continues calling itself without any termination condition.

Calling any function occupies space in the memory. And calling a function inside a function for infinite times can occupy almost every part of your computer memory. To tackle this problem, Python has implemented a Recursion Depth limit.

According to the Python recursion depth limit, by default, a recursion function can all itself only 1000 times. If the recursion exceeds this limit, the interpreter throws the error


RecursionError: maximum recursion depth exceeded while calling a Python object




.

To know the default Recursion limit for your program, you can use the

getrecursionlimit()

method from the Python sys modules.


Example

import sys

print("This default recursion limit is :", sys.getrecursionlimit())


Output

This default recursion limit is : 1000

If we look at the recursion error statement, we can divide it into two parts

  1. RecursionError
  2. maximum recursion depth exceeded while calling a Python object


1. RecursionError

RecursionError is one of the Python standard exceptions. It is a module exception that comes under the Python RuntimeError. Python raises this exception when it detects a maximum recursion depth in a program.


2. maximum recursion depth exceeded while calling a Python object

The »

maximum recursion depth exceeded while calling a Python object

» statement is the error message that tags along with the RecursionError exception. This error message tells us that a Python function has exceeded the number of recursion calls.


Common Example Scenario

Let us write a Python program using recursion that prints the

nth

number from a Fibonacci series. You can even write this program using the for loop.

In the

Fibonacci series

, the first two numbers are 0 and 1; the following numbers are calculated with the sum of the previous two numbers.


Program

# recursive function to find the nth Fibonacci number
def n_fibonacci(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return n_fibonacci(n-1)+n_fibonacci(n-2)
#
n=10

print(f"The {n} st/nd/th Fibonacci number is: ",n_fibonacci(n-1))


Output

The 10 st/nd/th Fibonacci number is: 34

The above program is correct, and it also shows the correct output. But if we change the value of

n=10

to

n=1005

, it will raise the error.


Program

# recursive function to find the nth Fibonacci number
def n_fibonacci(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return n_fibonacci(n-1)+n_fibonacci(n-2)
#out of the recursion range
n=1005

print(f"The {n}st/nd/th Fibonacci number is: ",n_fibonacci(n-1))


Output

RecursionError: maximum recursion depth exceeded in comparison

You can see that we receive the RecursionError with a different Error message. This is because the error message changes according to the operation we perform inside the function.

Here, it displays

»

maximum recursion depth exceeded in comparison

«.

This is because after exceeding the recursion limit, the Python interpreter can also not perform the comparison operator inside the recursion.


Solution

Python provides a

setrecursionlimit()

method that accepts an integer value as an argument and sets it as a recursion limit for the program. We can use this method to increase the default recursion depth limit.


Note:

The

setrecursionlimit()

method is also limited and can only increase the recursion limit depth to 3500.

To solve the above example, we can increase the recursion limit to 2000 using the

setrecursionlimit()

method.


Example

import sys
# increase the recursion limit
sys.setrecursionlimit(2000)

# recursive function to find the nth fibonacci number
def n_fibonacci(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return n_fibonacci(n-1)+n_fibonacci(n-2)
#now in recursion range
n=1005

print(f"the {n}st/nd/th fibonacci number is: ",n_fibonacci(n-1))


Output

the 1005 st/nd/th fibonacci number is: 482051511617926448416241857411039626258600330733909004920469712704382351844831823569922886993050824175326520025449797859766560885196970738202943545195859929088936259370887605815413541849563887924611727164704130

Executing the above program may take 10 to 20 minutes to finish because it calls the function repeatedly 2000 times.


Wrapping Up!

The

RecursionError

occurs when a recursion call exceeds the default recursion depth limit. When you encounter this error in your Python program, you must consider using an iterative approach to solve the problem. Using iterative statements like

for

and

while

loop, we can perform the desired action quickly and efficiently.

However, if you wish to solve your problem recursively, in that case, you can use them

setrecursivelimit()

to increase the default limit of the recursion call.

If you still get this error in your Python program, you can share your code in the comment section. We will try to help you with debugging.


People are also reading:

  • Python FileNotFoundError: [Errno 2] No such file or directory Solution

  • How to Remove Last Character from Python String?

  • Python SyntaxError: non-default argument follows default argument Solution

  • What is CubicWeb in Python?

  • Python TypeError: cannot unpack non-iterable NoneType object Solution

  • What is Python Pickle Module?

  • Python IndentationError: expected an indented block Solution

  • What is Web2Py in Python?

  • Python NameError: name ‘self’ is not defined Solution

  • What is TurboGears in Python?

When running a Python program, you might encounter the following error:

RecursionError: maximum recursion depth exceeded
 while calling a Python object

After doing some research, I found that this error occurs when a recursive function exceeded the default recursion limit set by Python, which is 1000 times.

Usually, this error occurs because of 2 possible scenarios:

  • You don’t have a base case to stop the recursion
  • Your recursive code requires more than 1000 depth

This tutorial will help you solve the error in both scenarios.

You don’t have a base case to stop the recursion

In practice, a recursive function will always call itself until a specific condition is met that stops the recursion.

That specific condition is also known as the base case, and your code must be able to reach that condition to stop running.

For example, the following countup() function prints the number n recursively:

def countup(n):
    print(n)
    countup(n + 1)


countup(1)

But since there’s no base case in this function, it will call itself forever, eventually causing a stack overflow.

To prevent the code from running forever, Python placed a soft limit on recursion to 1000 depth. This means when the function calls itself up to 1000 times, Python stops the execution and raises an error:

...
996
997
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    countup(1)
  File "main.py", line 3, in countup
    countup(n + 1)
  File "main.py", line 3, in countup
    countup(n + 1)
  File "main.py", line 3, in countup
    countup(n + 1)
  [Previous line repeated 993 more times]
  File "main.py", line 2, in countup
    print(n)
RecursionError: maximum recursion depth exceeded
 while calling a Python object

To resolve this error, you need to add a base case that prevents the recursion from running infinitely.

For example, stop the countup() function when it reaches 10 as shown below:

def countup(n):
    print(n)
    if n < 10:
        countup(n + 1)


countup(1)

This way, the countup() function will only be called as long as the n variable is less than 10.

This code won’t cause a RecursionError because as soon as the n variable is 10 or greater, the recursion won’t happen.

Your recursive code requires more than 1000 depth

Python sets the limit of recursion to 1000 to avoid recursive code repeating forever.

You can find this out by calling the getrecursionlimit() function from the sys module:

import sys

print(sys.getrecursionlimit())  

# Output: 1000

To get over this limitation, you can set the recursion limit using the setrecursionlimit() function.

This code modifies the recursion limit to 1500:

import sys

sys.setrecursionlimit(1500)

But keep in mind that increasing the limit too many would degrade the performance of Python itself.

If you could, you should use the iterative approach using a while loop instead of recursion. For example, here’s a modified countup() function that uses the iterative approach:

def countup(n):
    while n < 10:
        print(n)
        n += 1

countup(1)

You can use the base case as the condition that tells the while loop when to stop, and do the required operations inside the while block. At the end of the block, add an operation that allows the while loop to reach the base case.

Conclusion

Python raises the RecursionError: maximum recursion depth exceeded while calling a Python object when your recursive code exceeded the maximum recursion depth, which is set to 1000 by default.

To resolve this error, you need to create a base case to stop the recursion from going forever, and make sure that the base case can be reached within the allowed recursion depth.

You can change the recursion depth limit, or you can also use an iterative approach.

I hope this tutorial helps. See you in other tutorials! 👋

Table of Contents
Hide
  1. What is Recursion?
  2. A classic example of recursion
  3. Why does Python throw maximum recursion depth exceeded in comparison?
  4. How to check maximum recursion depth in Python?
  5. How do you fix the Recursionerror maximum recursion depth exceeded while calling a Python Object?
  6. Closing thoughts

Before jumping into an error, maximum recursion depth exceeded in comparison. Let’s first understand the basics of recursion and how recursion works in Python.

What is Recursion?

Recursion in computer language is a process in which a function calls itself directly or indirectly, and the corresponding function is called a recursive function. 

A classic example of recursion

The most classic example of recursive programming everyone would have learned the factorial of a number. Factorial of a number is the product of all positive integers less than or equal to a given positive integer.

For example, factorial(5) is 5*4*3*2*1, and factorial(3) is 3*2*1. 

Similarly, you can use recursive in many other scenarios like the Fibonacci seriesTower of HanoiTree TraversalsDFS of Graph, etc.

As we already know, recursive functions call by itself directly or indirectly, and during this process, the execution should go on infinitely.

Python limits the number of times a recursive function can call by itself to ensure it does not execute infinitely and cause a stack overflow error.

How to check maximum recursion depth in Python?

You can check the maximum recursion depth in Python using the code sys.getrecursionlimit(). Python doesn’t have excellent support for recursion because of its lack of TRE (Tail Recursion Elimination). By default, the recursion limit set in Python is 1000.

def fibonacci(n):
	if n <= 1:
		return n
	else:
		return(fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(1500))

#Output RecursionError: maximum recursion depth exceeded in comparison

How do you fix the Recursionerror maximum recursion depth exceeded while calling a Python Object?

Let’s write a recursive function to calculate the Fibonacci series for a given number.

Since you are finding a Fibonacci of 1500 and the default recursion limit in Python is 1000, you will get an error stating “RecursionError: maximum recursion depth exceeded in comparison.”

This can be fixed by increasing the recursion limit in Python, below is the snippet on how you can increase the recursion limit.

import sys
sys.setrecursionlimit(1500)

Closing thoughts

This code sets the maximum recursion depth to 1500, and you could even change this to a higher limit. However, it is not recommended to perform this operation as the default limit is mostly good enough, and Python isn’t a functional language, and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

  • Ошибка maximum call stack size exceeded
  • Ошибка max payne requires a directx 8 compatible display adapter
  • Ошибка max payne 2 exception in startupinit directory data not found
  • Ошибка max failed skip attempts
  • Ошибка maps ini city car driving