I arose a doubt about the finalizer method __del__
.
The __del__
method is called just before the object is cleaned up, but this method can even resurrect the object. Now I have noticed that in Python 2.7 the finalizer is called everytime the object's reference counter drops zero (even if the object was already resurrected), insted in Python3.4 it is called just once for all the entire life of the object, so if it is resurrected and then it counter drops to zero the finalizer method is not called anymore.
From the PEP 442 I read that in python 3.4 this choise was due to prevent resurrecting zombies:
However, if the object was already finalized, then the finalizer isn't called. This prevents us from finalizing zombies
My doubt is that I can't figure out how this solution can prevent us from finalizing zombies, can you make me some concrete examples? In addition the object can be resurrected only once.
Suppose we have the following class:
class RefCycle:
def __init__(self):
self.refcycle = self
def __del__(self):
print('finalizing')
print(self.refcycle)
and we create and collect a cyclic isolate:
RefCycle()
import gc
gc.collect()
When the garbage collector detects the cyclic isolate, it calls the RefCycle
instance's finalizer. Then, it starts to break references. When it clears the self.refcycle
attribute, the object's refcount drops to 0.
This is where it's important that finalized objects are not refinalized. If that "already finalized" flag weren't there, the object would be refinalized as a consequence of the refcount going to 0. Since the garbage collector has already messed with the object's attributes, this would be a very bad thing. The "already finalized" flag protects us from this scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With