Get all the instances of one class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri May 16 20:04:31 EDT 2008


En Fri, 16 May 2008 20:44:00 -0300, Terry <terry.yinzhe at gmail.com>  
escribió:

> Is there a simple way to get all the instances of one class? I mean
> without any additional change to the class.

Try with gc.get_referrers()

py> import gc
py> class A(object): pass
...
py> a,b,c = A(),A(),A()
py> A
<class __main__.A at 0x00A3F4E0>
py> for item in gc.get_referrers(A): print type(item)
...
<type 'getset_descriptor'>
<type 'getset_descriptor'>
<type 'tuple'>
<class '__main__.A'>
<class '__main__.A'>
<class '__main__.A'>
<type 'dict'>
<type 'dict'>

We need to filter that list, keeping only A's instances:

py> [item for item in gc.get_referrers(A) if isinstance(item,A)]
[<__main__.A object at 0x00A40DC8>, <__main__.A object at 0x00A40DF0>,  
<__main__.A object at 0x00A40E18>]

-- 
Gabriel Genellina




More information about the Python-list mailing list