Why is the destructor called when the CPython garbage collector is disabled?

Posted by Frederik on Stack Overflow See other posts from Stack Overflow or by Frederik
Published on 2010-04-05T11:28:14Z Indexed on 2010/04/05 11:33 UTC
Read the original article Hit count: 275

I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up:

  1. Disable the GC.
  2. Create an object, then remove a reference to it.
  3. The object is destroyed and the __del__ method is called.

I thought this would only happen if the garbage collector was enabled. Can someone explain why this happens? Is there a way to defer calling the destructor?

import gc
import unittest

_destroyed = False

class MyClass(object):

    def __del__(self):
        global _destroyed
        _destroyed = True

class GarbageCollectionTest(unittest.TestCase):

    def testExplicitGarbageCollection(self):
        gc.disable()
        ref = MyClass()
        ref = None
        # The next test fails. 
        # The object is automatically destroyed even with the collector turned off.
        self.assertFalse(_destroyed) 
        gc.collect()
        self.assertTrue(_destroyed)

if __name__=='__main__':
    unittest.main()

Disclaimer: this code is not meant for production -- I've already noted that this is very implementation-specific and does not work on Jython.

© Stack Overflow or respective owner

Related posts about cpython

Related posts about python