[Tutor] How to find all current instances of a class?

Mats Wichmann mats at wichmann.us
Sun Jun 21 15:46:39 EDT 2020


On 6/21/20 1:34 PM, boB Stepp wrote:
> I had (perhaps) naively hoped that classes had dunder methods to list
> all current instances associated with that class, but if there is
> something that simple I have yet to find it.  Does an easy, built-in
> method exist to list all current instances of a particular class?

Python doesn't track this, so you gotta do it yourself.

Two thoughts:  (1) find all the objects - the garbage collector knows
this - and filter that. (2) have the class track it - you can make a
class attribute and add a weak reference to it each time the class
initializer is called. Or (3) some other way I didn't think of (pretty
much guaranteed to exist)

For the former, I *think* this will be good enough, it's off the top of
my head and so untested:

import gc

instances = [obj for obj in gc.get_objects() if isinstance(obj,
ClassWeWantToTrack)]


More information about the Tutor mailing list