Python: find all instances of a class with gc.get_objects() 0 ▲ Adam Johnson 145 days ago · Tech · hide · Fediverse post Here’s a lovely hack that I’ve used when machete-mode debugging. Say you have a class, and you want to find its live instances, perhaps to check how many there are or what value a certain attribute has across them. Normally you'd have to alter the class initialization to store its instances in a collection, like a WeakSet, but making such edits slows down debugging and isn’t always possible. The approach in this post uses the garbage collector module, gc, to leverage its already-tracked references to the class in question, no restart required. The function gc.get_objects() traverses (nearly) all live objects tracked by the garbage collector and returns a list of them. (It misses some kinds of special objects that are not tracked by the garbage collector, but that’s very rarely a concern.) We can use it with a list comprehension to filter for instances of a given class: import gc instances = [obj for obj in gc.get_objects() if isinstance(obj, MyClass)] This approach can be slow,… Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town