wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

Python Inner class raises recursion error

Open koldakov opened this issue 1 year ago • 5 comments

Haven't seen anyone raised this before.

import sys

sys.setrecursionlimit(4)


class Foo:
    class Foo:
        foo = 1

Raises

RecursionError: maximum recursion depth exceeded while calling a Python object

koldakov avatar Apr 12 '24 18:04 koldakov

This is interesting! If we go a step further and set the recursion limit to 2. The function itself will raises the error. If we set it to 3, it will not allow you to define a class

>>> import sys
>>> sys.setrecursionlimit(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RecursionError: cannot set the recursion limit to 2 at the recursion depth 2: the limit is too low
>>> sys.setrecursionlimit(3)
>>> class Foo:
...     foo = 1
... 
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 62, in apport_excepthook
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 26, in enabled
RecursionError: maximum recursion depth exceeded while calling a Python object

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded while calling a Python object

ngala avatar Apr 13 '24 11:04 ngala

Requires further investigation, looks like depends on python version as well.

For example, python 3.12 doesn't raise this error, but python 3.8/3.9/3.10 does.

At the same time python 3.8/3.9/3.10 don't allow to set recursion limit to 2: RecursionError: cannot set the recursion limit to 2 at the recursion depth 2: the limit is too low.

Also, python 2.7 doesn't raise RecursionError: maximum recursion depth exceeded while calling a Python object if limit is 3 or more.

@ngala

koldakov avatar Apr 13 '24 17:04 koldakov

Yes, I had executed the code on Python 3.10. Python 3.12 gives error if we set the limit to 1 which seems fine, I guess

ngala avatar Apr 14 '24 07:04 ngala

Hey @koldakov , could you please write the summarized explanation and make a PR? If it is possible, of course. Or maybe @ngala is interested in making such task?

nifadyev avatar Oct 16 '24 08:10 nifadyev

Hi @nifadyev, currently I'm swamped, but I'll take a shot if ngala won't do it first

koldakov avatar Oct 25 '24 13:10 koldakov