2 hours ago · Tech · hide · 0 comments

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,…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.