[Tutor] Object destruction

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 24 19:07:11 EDT 2022


On 24/05/2022 14:27, Dimitar Ivanov wrote:

> I'm trying to come up with a (working) design of tracking an object
> throughout its lifecycle but I'm unable to find quite what I'm looking for,

Thats because I think you are looking for the wrong thing.
I think you ae getting confused between objects and names.

>     def __init__(self, name):
>         self.name = name
>         self._finalizer = weakref.finalize(self, self.finalize)

This only registers a metjod that will be called when the object
is garbage collected. That in turn will be "some time"
after the last strong reference is broken.

> Here, I have the static object that "traces" those objects:
> 
> class Tracer:
> 
>     traced_objects = []
> 
>     @staticmethod
>     def trace(some_object):
>         Tracer.traced_objects.append(some_object)
> 
>     @staticmethod
>     def untrace(some_object):
>         Tracer.traced_objects.remove(some_object)

This seems like a pointless class. It could (should?)
just be two functions.

> if __name__ == '__main__':
>     objectOne = TestClass("Object1")
>     objectTwo = TestClass("Object2")
>     thrd1 = Thread(target=objectOne.do_stuff)
>     thrd2 = Thread(target=objectTwo.do_stuff)
>     thrd1.start()
>     thrd2.start()
>     thrd1.join()
>     thrd2.join()
>     del objectOne
>     del objectTwo

But these del statements don't delete the object, they simply
delete the name from the namespace. Doing so reduces the reference
count but does not delete the object. (As you've discovered)

So which are you really interested in? Is it the lifecycle of
the object? The lifecycle of the name? Or the references?

> It seems like the Finalizer is only kicking off the objects' finalize
> methods once the program exits, which, if I'm reading the documentation
> right, is the correct behaviour

Only because that's the point that the object is destroyed.
You are correctly monitoring the object lifecycle.

; however, I need that finalize method
> kicked off as soon as any reference to those objects is removed. 

Any reference?

a = MyClass()
b = a
objects = [a,b]
del a
del b
del objects

Should that call the finalizer once? or twice? or three times? or four?
And when?

> Can I achieve that in any way?

You need to be clearer what you want.
You are already tracking object lifecycles successfully.
You are not tracking references, that would need a different
approach entirely.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list