OOP - iterable class: how to delete one of its objects ?

Rhodri James rhodri at kynesim.co.uk
Fri Nov 1 15:40:10 EDT 2019


On 01/11/2019 19:15, R.Wieser wrote:
> Hello all,
> 
> I've created a class from which I can iterate all its instanciated objects
> (using an "instances" list).    The problem is that I now cannot seem to
> delete an object anymore, AFAIK as a copy of its "self" is still inside the
> "instances" list.
> 
> Object in question:
> - - - - - - - - - - - - - - - -
> class TheObject:
>      instances = []
> 
>      def __init__(self):
>          self.instances.append(self)
> 
>      def __del__(self):
>          print("Deleted!")
> - - - - - - - - - - - - - - - -
> 
> The question: How can I keep the class iterable, but still have it delete
> itself when asked.

Use weak references.  A WeakSet 
(https://docs.python.org/3/library/weakref.html#weakref.WeakSet) is 
probably what you want.

The idea is that the reference to the instance kept by the WeakSet 
doesn't contribute to the reference count.  This won't automatically 
delete the reference from the WeakSet when the instance goes away, 
you'll want to set a finalizer for that, but the documentation covers 
what you want to know fairly clearly.  Trust me, I was doing exactly 
this a week or so ago, and it's pretty straightforward.

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-list mailing list