G
Guest
Hello all,
I'd like some advices from more experienced python users. I want to
have a class in my python application that does not allow multiple
instance with same "name".
I want to have a class (call it kls) that behave at least following way:
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.
My question is if i can find metaclass or something that allows me to
create such class easily. I tried to search such thing on internet, but
I even don't know how to call this kind of thing. It is in a sense like
singleton, but less restrictive.
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.
Any other suggestions are very much appreciated as well.
I'd like some advices from more experienced python users. I want to
have a class in my python application that does not allow multiple
instance with same "name".
I want to have a class (call it kls) that behave at least following way:
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.
My question is if i can find metaclass or something that allows me to
create such class easily. I tried to search such thing on internet, but
I even don't know how to call this kind of thing. It is in a sense like
singleton, but less restrictive.
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.
Any other suggestions are very much appreciated as well.