Search code examples
pythongarbage-collectionfinalizer

Determine whether object has been finalized


One of the effects of the GC changes that happened in Python 3.4 is that a gc-tracked object will only have its __del__ method called once, even if the first __del__ call resurrects the object:

>>> class Foo(object):
...     def __del__(self):
...         print('__del__')
...         global x
...         x = self
... 
>>> x = Foo()
>>> del x
__del__
>>> del x
>>> 

(Untracked objects currently behave differently, since they don't have the flag that indicates already-finalized status. You can see this by inserting __slots__ = () in the above class definition. I'm not sure whether whether this is a bug or a known and accepted behavior difference.)

For debugging purposes, it would be useful to be able to determine if an object has had its __del__ method called. One option would be to insert a line in __del__ that sets an indicator flag, but that requires advance preparation, and it may not be possible for objects with __del__ written in C, such as generators.

Is it possible to determine whether an object has been finalized, without modifying its __del__ method?


Solution

  • In Python 3.9, this can be tested using gc.is_finalized(obj).