Get all the instances of one class

Diez B. Roggisch deets at nospam.web.de
Sun May 18 11:35:32 EDT 2008


Terry schrieb:
> On May 17, 8:04 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Fri, 16 May 2008 20:44:00 -0300, Terry <terry.yin... 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
> 
> But I saw in the help that we should "Avoid using get_referrers() for
> any purpose other than debugging. "

Yes, because using it do is very resource-consuming and shouldn't be 
done. Why don't you tell us what you are after here & then we might come 
up with a better solution?

Diez



More information about the Python-list mailing list