[Tutor] Object destruction

Cameron Simpson cs at cskk.id.au
Tue May 24 19:10:03 EDT 2022


On 24May2022 14:27, Dimitar Ivanov <dimitarxivanov at gmail.com> 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,
>so I hope you folks will be able to give me some tips.
>
>I have an object that is being created and I want to "trace" that object in
>a separate static class that other threads and objects will be able to
>access if necessary:
[...]
>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; however, I need that finalize method
>kicked off as soon as any reference to those objects is removed. Can I
>achieve that in any way?

_Any_ reference, or when the final-reference-except-for-your-tracer 
reference is removed? For the latter, see the weakref module:
https://docs.python.org/3/library/weakref.html#module-weakref

For making references to objects which do not contribute to their 
reference count.

My SingletonMixin class uses a WeakValueDictionary to keep references to 
existing instances without extending their lifespan. A 
WeakValueDictionary may well fit your use case.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list