473,804 Members | 1,992 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class that keeps track of instances

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='myn ame'), 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.WeakVal ueDictionary 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.

--
yosuke kimura
Center for Energy and Environmental Resources
The Univ. of Texas at Austin, USA
Sep 17 '07 #1
3 1500
<yo****@ccwf.cc .utexas.eduwrit es:
1) New instance has to have a property called 'name'
2) When instance is attemped to created, e.g., x=kls(name='myn ame'), 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.valu es())

class kls(object):
__metaclass__ = Meta
cache = weakref.WeakVal ueDictionary()
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.WeakVal ueDictionary 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.
Sep 17 '07 #2
On 17 sep, 19:10, <yos...@ccwf.cc .utexas.eduwrot e:
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='myn ame'), and
there already exists an instance with obj.name =='myname', that
pre-existing instance is returned, instead of making new one.
For all of this I would use the __new__ method.
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.
I'd store a WeakValueDictio nary using the name as a key. Instead of a
property 'all', I'd use a method 'get_all_instan ces()' that should
call values() on the weak dictionary.
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.
Have you tried the Python Cookbook?
Assuming that I have to write it on my own, what should I do? I tried
to implement it using weakref.WeakVal ueDictionary 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.
A WeakValueDictio nary should work. If the instance is not deleted when
you expect, maybe there are other references somewhere, or the garbage
collector didn't run yet.

Ok, finally I wrote an example:

pyfrom weakref import WeakValueDictio nary
py>
pyclass OneOfAKind(obje ct):
.... _instances = WeakValueDictio nary()
.... def __new__(cls, name):
.... inst = cls._instances. get(name, None)
.... if inst is None:
.... inst = cls._instances[name] = super(OneOfAKin d,
cls).__new__(cl s
)
.... inst.name = name
.... return inst
.... @classmethod
.... def get_all_instanc es(cls):
.... return cls._instances. values()
.... __str__ = __repr__ = lambda self: '%s(%r)' %
(self.__class__ .__name__, s
elf.name)
....
pya = OneOfAKind('A')
pyb = OneOfAKind('A')
pyassert b is a
pyc = OneOfAKind('C')
pyassert c is not a
pyprint OneOfAKind.get_ all_instances()
[OneOfAKind('A') , OneOfAKind('C')]
pydel c
pyimport gc
pygc.collect()
17
pyprint OneOfAKind.get_ all_instances()
[OneOfAKind('A')]
pydel a
pydel b
pygc.collect()
0
pyprint OneOfAKind.get_ all_instances()
[]
py>

--
Gabriel Genellina
Sep 17 '07 #3
yo****@ccwf.cc. utexas.edu wrote:
I want to have a class in my python application that does not allow
multiple instance with same "name".
Thank you very much for very quick and precise answers to my questions!
input for garbage collector and id are appreciated as well. I head to
bookstore for the cookbook (O'reily's, right?). i thought it was too
cryptic but maybe time for met to revisit the book.

--
yosuke kimura
Center for Energy and Environmental Resources
The Univ. of Texas at Austin, USA
Sep 18 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3198
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
5
2074
by: Laszlo Zsolt Nagy | last post by:
Hughes, Chad O wrote: > Is there any way to create a class method? I can create a class > variable like this: > Hmm, seeing this post, I have decided to implement a 'classproperty' descriptor. But I could not. This is what I imagined: class A(object):
6
2727
by: MooseMiester | last post by:
This little program just doesn't do what I think it should and I cannot understand what the problem is. I'm running Python 2.4 on Windoze XP. It contains an album class, an album collection class, a track class, and a track collection class. It seems confused about which instance is which -- when it says Albums.Tracks.Count() the two instances are unique, but when it says Album.Tracks you get both instances combined. It's as if all...
44
2962
by: Steven D'Aprano | last post by:
I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! "Abstract class" isn't right, because that implies that you should subclass the class and then instantiate the...
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10088
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.