How can I list all created objects in Python?

I have lengthy processes that may have a resource leak. How can I get a list of all instances of objects (maybe just a certain class) in my environment?

+6
source share
3 answers

Try gc.get_objects() :

 >>> import gc >>> >>> class Foo: pass ... >>> f1 = Foo() >>> >>> [o for o in gc.get_objects() if isinstance(o, Foo)] [<__main__.Foo instance at 0x2d2288>] >>> >>> f2 = Foo() >>> >>> [o for o in gc.get_objects() if isinstance(o, Foo)] [<__main__.Foo instance at 0x2d2288>, <__main__.Foo instance at 0x2d22b0>] 
+7
source

There are several ways that you should combine to a large extent. I have used this module in the past to accurately verify that memory leaks

https://mg.pov.lt/objgraph/

This can cause your process to use TON more memory and be quite slow, though, depending on how you use it.

+3
source

All created objects (I assume for Python itself in one module):

globals().keys() .

For all those that are instances of only a particular class:

filter(lambda x: isinstance(x, some_class), globals().keys()) .

-1
source

Source: https://habr.com/ru/post/958345/


All Articles