How To capture an id into an array..

Peter Otten __peter__ at web.de
Mon Mar 29 09:03:37 CEST 2004


Josiah Carlson wrote:

> BALAJI RAMAN wrote:
>> Hello everybody!!!
>> 
>> I'm pretty much new to this OOP...
>> 
>> I have a problem..
>> 
>> Here is a part of code that I'm writing
>> 
>> class V(E):
>>     """ This is a variable for MPY"""
>>     def __init__(self):
>>         print id(self)
>>         check=[]
>>         check.append(id(self))
>>         self.val = None
>> 
>> what I do is call say v1=V() so it means that v1 belongs to the
>> variable class..
>> 
>> Again if I call v2=V() so now v2 also belong to this class.. I want
>> to keep a track of all the instances of this class.. and store their
>> ids in an array..
>> 
>> any help in this regards is appreciated...
> 
> The poor way of doing it is...
> 
> class V(E):
>      check = []
>      def __init__(self):
>          print id(self)
>          self.check.append(id(self))
>          self.val = None
> 
> The reason it is poor is because if an object is deleted, its id could
> be reused.
> 
> Instead, you should use weak references.  I've found the following to be
> useful on occasion...
> 
> import weakref
> 
> class V(E):
>      check = {}
>      def __init__(self):
>          #create a weak reference to yourself
>          #place it in the __olist
>          self.check[id(self)] = weakref.ref(self)
>      def __del__(self):
>          del self.check[id(self)]
>      def __repr__(self):
>          return str(id(self))
>      def get_olist(self):
>          #this creates a hard reference to every object
>          return [o() for o in self.check.values() if o() is not None]
> 
>   - Josiah

The __del__ method may not always be called. I find the WeakValueDictionary
handy (which internally uses callbacks I think).

import weakref 

class V:
    all = weakref.WeakValueDictionary() # required
    def __init__(self, name):
        self.name = name
        V.all[id(self)] = self # required
    def __str__(self):
        return self.name
    __repr__ = __str__

v1 = V("v1")
v2 = V("v2")
print V.all.values()
del v1
print V.all.values()

Peter





More information about the Python-list mailing list