[Python] Why this python code triggers RecursionError [closed]

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I ran the following code and it triggered lots of repeated printouts and the RecursionEorr. Can someone help explain the reason please? Thank you!

    The code

    class Customer:
    def __init__(self, id, name):
    self.id=id
    self.name=name

    def __eq__(self, other):
    print('simulated default __eq__ is called')
    return self==other


    c1=Customer(123, 'A')
    c2=Customer(123, 'A')
    print(c1==c2)


    Part of the log

    simulated default __eq__ is called
    simulated default __eq__ is called
    simulated default __eq__ is called
    simulated default __eq__ is called
    simulated default __eq__ is called
    simulated default __eq__ is called
    simulated default __eq__ is called
    ---------------------------------------------------------------------------
    RecursionError Traceback (most recent call last)
    Cell In[5], line 13
    11 c1=Customer(123, 'A')
    12 c2=Customer(123, 'A')
    ---> 13 print(c1==c2)

    Cell In[5], line 8, in Customer.__eq__(self, other)
    6 def __eq__(self, other):
    7 print('simulated default __eq__ is called')
    ----> 8 return self==other

    Cell In[5], line 8, in Customer.__eq__(self, other)
    6 def __eq__(self, other):
    7 print('simulated default __eq__ is called')
    ----> 8 return self==other

    [... skipping similar frames: Customer.__eq__ at line 8 (990 times)]

    Cell In[5], line 8, in Customer.__eq__(self, other)
    6 def __eq__(self, other):
    7 print('simulated default __eq__ is called')
    ----> 8 return self==other

    Cell In[5], line 7, in Customer.__eq__(self, other)
    6 def __eq__(self, other):
    ----> 7 print('simulated default __eq__ is called')
    8 return self==other

    File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\ipykernel\iostream.py:684, in OutStream.write(self, string)
    682 # only touch the buffer in the IO thread to avoid races
    683 with self._buffer_lock:
    --> 684 self._buffers[frozenset(parent.items())].write(string)
    685 if is_child:
    686 # mp.Pool cannot be trusted to flush promptly (or ever),
    687 # and this helps.
    688 if self._subprocess_flush_pending:

    RecursionError: maximum recursion depth exceeded in comparison


    PS: I switched to use this code 'return self is other', which resolved the issue anyway.

    Continue reading...

Compartilhe esta Página