Maximum recursion depth exceeded in comparison python как исправить


Скачай курс
в приложении
Перейти в приложение
Открыть мобильную версию сайта
© 2013 — 2023. Stepik
Наши условия использования и конфиденциальности

Public user contributions licensed under cc-wiki license with attribution required
Python-сообщество
![]()
- Начало
- » Python для новичков
- » RuntimeError: maximum recursion depth exceeded
#1 Июнь 17, 2012 13:34:09
Serbis От: Зарегистрирован: 2012-02-13 Сообщения: 38 Репутация: 0 Профиль Отправить e-mail
RuntimeError: maximum recursion depth exceeded
Вопрос конечно немного не сюда, он скорее относится к теме QT, но имеет несколько промежуточный характер, поэтому я опубликую его здесь. Значит в чем суть. Имеется таблица, с обработчиком(слотом) события(сигнала), изменения содержимого ячейки. Смысл обработчика таков — проверить совершен ли ввод в ячейку соответствующей строки, и если да, то дополнить не введенные нули. Суть в чем, все работает как нужно, за одним моментом — происходит RuntimeError, но не приводивший до поры до времени к крешу программы, теперь приводит. Вообще, если я правильно понял суть, происходит превышение лимита обработки прерывания от клавиатуры. Так как опытным путем удалось выяснить что slot_cellChange вызывается 1000 раз, на 1001 происходит сбой. Но как с этим бороться не имею представления.
self.connect(self.table, QtCore.SIGNAL('cellChanged (int, int)'), lambda row = 1: self.slot_cellChange(row)) def slot_cellChange(self, row): lit = self.field[row] if lit == 'Stock': it = self.table.item(row, 1) self.table.setItem(row, 1, QtGui.QTableWidgetItem(format(float(str(it.text())), ".3f")))
Traceback (most recent call last):
File “/home/serbis/Prog/python/b3/sources/createa/table.py”, line 28, in
self.connect(self.table, QtCore.SIGNAL(‘cellChanged (int, int)’), lambda row = 1: self.slot_cellChange(row))
RuntimeError
Error in sys.excepthook:
Traceback (most recent call last):
File “/usr/lib/python2.6/dist-packages/apport_python_hook.py”, line 44, in apport_excepthook
if exc_type in (KeyboardInterrupt, ):
RuntimeError: maximum recursion depth exceeded in cmp
Original exception was:
Traceback (most recent call last):
File “/home/serbis/Prog/python/b3/sources/createa/table.py”, line 28, in
self.connect(self.table, QtCore.SIGNAL(‘cellChanged (int, int)’), lambda row = 1: self.slot_cellChange(row))
RuntimeError: maximum recursion depth exceeded
How to Fix RecursionError in Python

The Python RecursionError is an exception that occurs when the maximum recursion depth is exceeded. This typically occurs when a function calls itself recursively, and the recursion doesn’t have a proper stopping condition (base case).
What Causes RecursionError
A RecursionError in Python is caused by a function calling itself recursively without a proper base case. Python has a limit on the number of times a function can call itself recursively. This is to ensure that the function does not execute indefinitely. If this limit is exceeded by a recursive function, a RecursionError is raised.
Python RecursionError Example
Here’s an example of a Python RecursionError thrown when calling a recursive function that does not have a base case:
def func(): func() func()
Since the recursive function func() does not have a terminating condition, calling it creates an infinite loop as the function keeps calling itself over and over again until the RecursionError: maximum recursion depth exceeded error occurs:
Traceback (most recent call last): File "test.py", line 4, in func() File "test.py", line 2, in func func() File "test.py", line 2, in func func() File "test.py", line 2, in func func() [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded
How to Fix RecursionError in Python
Here are some approaches to fix a recursion error in Python:
- Adding a base case: The most common cause of a recursion error is that the function does not have a base case to stop the recursion. In such cases, a base case can be added to the function that stops recursion when a condition is met.
- Increasing the recursion limit: Python has a default maximum recursion depth of 1000. If a function exceeds this limit, it can be increased using the sys.setrecursionlimit(n) function. Developers should be careful when increasing the limit as this can cause a crash if the recursion is not properly controlled.
- Using an iterative approach: If a recursive approach is causing a recursion error, it may be possible to use an iterative approach instead e.g. a for or while loop. This can reduce the risk of hitting the maximum recursion depth, and in some cases can also lead to more efficient and easier to understand code.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
RecursionError
Исключение, возникающее в случае обнаружения рекурсивного вызова.
Поднимается, когда интерпретатор обнаруживает что достигнут предел для рекурсивных вызовов (см. sys.getrecursionlimit() ).
def loop():
loop()
loop() # RecursionError: maximum recursion depth exceeded
Пример выше вызывает «вечную» рекурсию и поднимает рассматриваемое исключение.
До -py3.5 ошибки рекурсии поднимали исключение — RuntimeError.
Синонимы поиска: RecursionError
