I would like to be able to create a list of all instances of a class. Another post here described how to do it by appending to a list during the __init__ routine but since I am a real Python newbie (and even more of a newbie to classes) I was hoping someone could post a simple code example to show a real world example of this. Thanks in advance.

Dani AI

Generated

If you want to list the instances without keeping them alive, track them with weak references. A weakref.WeakSet holds references that do not inhibit garbage collection, so you see only currently live objects. This is a drop-in pattern you can reuse across classes.

import weakref

class Thingy:
    _instances = weakref.WeakSet()

    def __init__(self, *args, **kwargs):
        type(self)._instances.add(self)

    @classmethod
    def live_instances(cls):
        return list(cls._instances)

# Example usage
t1, t2 = Thingy(), Thingy()
print(len(Thingy.live_instances()))  # 2
del t1
print(len(Thingy.live_instances()))  # 1 (after t1 is collected)

Notes:

  • If you use __slots__, make sure to include '__weakref__' (e.g., __slots__ = ('__weakref__', ...)) or instances cannot be weak-referenced.
  • For debugging only, you can inspect the heap with [o for o in __import__('gc').get_objects() if isinstance(o, Thingy)], but be aware this traverses all tracked objects and is slower. See the docs for weakref.WeakSet and gc.get_objects for details.

Recommended Answers

All 2 Replies

Well, here is an example

class Thingy(object):
    instances = []

    def __init__(self):
        self.instances.append(self)

def waste_time_and_memory():
    t = Thingy()

for i in range(5):
    waste_time_and_memory()

print Thingy.instances

""" My output -->
[<__main__.Thingy object at 0x7f0581777c50>, <__main__.Thingy object at 0x7f0581777c90>, <__main__.Thingy object at 0x7f0581777cd0>, <__main__.Thingy object at 0x7f0581777d10>, <__main__.Thingy object at 0x7f0581777d50>]
"""

The main problem is that Thingy objects are immortal unless you empty the list periodically.

commented: Just joined to say thanks for this workaround. I think I will continue finding nice solutions in this place. +0

Brilliant. That's just what I was after. So much easier to understand to actually see the code. Thanks for taking the time to help me.

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.