Get all the instances of one class

Nick Craig-Wood nick at craig-wood.com
Mon May 19 06:30:03 EDT 2008


Matt Nordhoff <mnordhoff at mattnordhoff.com> wrote:
>  Tommy Nordgren wrote:
> > class MyClass : a_base_class
> >       memberlist=[]
> > 
> > #  Insert object in memberlist when created;
> > #  note: objects won't be garbage collected until removed from memberlist.
> 
>  Just to say, if you wanted to go about it that way, you could avoid the
>  garbage collection problem by using weakrefs:
> 
> <http://docs.python.org/lib/module-weakref.html>

Eg...

from weakref import WeakKeyDictionary

class Test(object):
    _instances = WeakKeyDictionary()
    def __init__(self):
        self._instances[self] = True
        # your normal init stuff here
    @classmethod
    def instances(cls):
        return cls._instances.keys()

print Test.instances()
a = Test()
b = Test()
print Test.instances()
del a
print Test.instances()
del b
print Test.instances()

....

Which prints

[]
[<__main__.Test object at 0xb7d4eb6c>, <__main__.Test object at 0xb7d4eb4c>]
[<__main__.Test object at 0xb7d4eb6c>]
[]


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list