Get all the instances of one class

Terry terry.yinzhe at gmail.com
Sun May 18 19:42:05 EDT 2008


On May 18, 11:35 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> 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

I'm developing a message/state_machine based python program (I'm not
using stackless, plan to move to it later).
I want to collect all the state_machines (threads) and send them
'tick' message or 'quit' message.

Now I'm using a static member to collect the machines, just wonderring
if python already provide something like this.



More information about the Python-list mailing list