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?

Recommended Answers

All 4 Replies

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...

Sounds like that should work. Thanks!

Probably delete could be addressed by using WeakRefs...

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.