I have a long running processes which may have a resource leak. How can I obtain a list of all instantiated objects (possibly only of a particular class) in my environment?
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
Method 1 – Using the dir() function to list methods in a class. To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.
Practical Data Science using Python Any object, even a list, can be returned by a Python function. Create the list object within the function body, assign it to a variable, and then use the keyword "return" to return the list to the function's caller.
In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users. Important Points about Printing: Python uses __repr__ method if there is no __str__ method.
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>]
There's a few ways that you pretty much have to combine. I've used this module in the past to check for exactly that, memory leaks
https://mg.pov.lt/objgraph/
It can make your process use a TON more memory and be pretty slow though, depending on how you use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With