class that keeps track of instances

Hrvoje Niksic hniksic at xemacs.org
Mon Sep 17 18:56:02 EDT 2007


<yosuke at ccwf.cc.utexas.edu> writes:

> 1) New instance has to have a property called 'name'
> 2) When instance is attemped to created, e.g., x=kls(name='myname'), and
> there already exists an instance with obj.name =='myname', that
> pre-existing instance is returned, instead of making new one.  
> 3) A class property 'all' for class gives me a list of all the
> instances.  So kls.all lets me iterates through all instances.
> 4) When all the hard-link to an instance is deleted, the instance should
> be deleted, just like an instance from any regular class does.

class Meta(type):
  all = property(lambda type: type.cache.values())

class kls(object):
  __metaclass__ = Meta
  cache = weakref.WeakValueDictionary()
  def __new__(cls, name):
    if name in kls.cache:
        return kls.cache[name]
    self = object.__new__(cls)
    self.name = name
    kls.cache[name] = self
    return self

>>> x = kls(name='foo')
>>> x
<__main__.kls object at 0xb7d5dc8c>
>>> x is kls(name='foo')
True
>>> x is kls(name='bar')
False
>>> print kls.all        # only one instance, 'bar' was short-lived
[<__main__.kls object at 0xb7d5dc8c>]
>>> x = 'somethingelse'
>>> print kls.all
[]

> Assuming that I have to write it on my own, what should I do?  I
> tried to implement it using weakref.WeakValueDictionary and
> metaclass, but instance doesn't disappear when I think it should
> disappear.  I am also wondering if it is easier to keeping
> {name:id(obj)} would be a better solution.

The problem is that, given just an ID, you have no way to get a hold
of the actual object.



More information about the Python-list mailing list