Really, the title says it all. Is there any way to compile all the instances of a class into a list, or other such data structure?

9 Years
Discussion Span
Last Post by Gribouillis

I have done this on occasion. The easiest way to do this is have your __init__() routine append self to a list. If it's not "your" class I suppose you could override the __init__ method of the class.

Fortunately I never had to worry about deletes...


Probably delete could be addressed by using WeakRefs...

Indeed, you can store the instances in a weakref.WeakValueDictionary for example

from weakref import WeakValueDictionary

class A(object):
  instances = WeakValueDictionary()

  def __init__(self):
    self.instances[id(self)] = self

Instances disappear magically from the dictionary when their reference counts falls to 0.

Note that it's better to start a new thread than reviving an old one. The OP probably solved this problem a long time ago.

Edited by Gribouillis: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.