Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list all instantiated objects in Python?

Tags:

python

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?

like image 343
Mark Harrison Avatar asked Nov 18 '13 22:11

Mark Harrison


People also ask

Can I have a list of objects in Python?

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.

How do I see all the classes of a Python object?

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.

How do you return a list of objects in Python?

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.

How do you print all objects in a class Python?

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.


2 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>]
like image 143
arshajii Avatar answered Sep 27 '22 17:09

arshajii


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.

like image 40
Falmarri Avatar answered Sep 27 '22 17:09

Falmarri