pynexj
pynexj

Reputation: 20688

Example of "reference loop" which can prevent "__del__()" from being called?

(I'm using Python 3.6.5)

I'm debugging a production problem which seems to be caused by __del__ not being called. I added debug messages in both __init_ and __del__ and it turned out sometimes (when the product problem was hit) __del__ is not called.

I Googled a lot and based on my understanding there are 2 cases where __del__ may not be called:

  1. os._exit()
  2. Cyclic reference (or reference loop)

I'm quite sure we did not call os._exit() so I suspect the problem was most likely caused by some reference loop but I failed to figure out what a reference loop would look like. So could someone help give an example of reference loop which can prevent __del__ from being called?

Upvotes: 2

Views: 94

Answers (1)

pynexj
pynexj

Reputation: 20688

Seems like the PEP 0442 (Python 3.4) mentioned in the comment did not work for all scenarios. Just found an example from here (tested with Python 3.5.3):

[STEP 101] # cat ref_loop.py
class Foo():
    def __init__(self):
        print("now in __init__")
        self.foo = self

    def __del__(self):
        print("now in __del__")

foo = Foo()
exit()
[STEP 102] # python3 ref_loop.py
now in __init__
[STEP 103] # python3 --version
Python 3.5.3
[STEP 104] #

My another Python 3.6.5 can also reproduce it.

Note that if exit() is removed then __del__() will be called though I don't understand why.

Upvotes: 1

Related Questions