weakrefs and things that point to each other

Jonathan Gardner gardner at cardomain.com
Thu Jun 21 20:45:55 EDT 2001


Okay, here''s the idea. Object A can have many things of Class B. Object B 
can be had by many things of Class A. When A is destroyed, it wants to let 
B know that it no longer has it. When B is destroyed, it wants to let A 
know it no longer should have it.

So:
# Without weakrefs...
class A:
    def __init__(self):
        self.has = []

    def add(self, b):
        if b not in self.has:
            self.has.append(b)

    def remove(self, b):
        self.has.remove(b)

    def __del__(self):
        for b in self.has:
            b.removedfrom(self)

            
class B:
    def __init__(self):
        self.hadby = []

    def addedby(self, a):
        self.hadby.append(a)

    def removedfrom(self, a):
        self.hadby.remove(a)

    def __del__(self):
        for a in self.hadby:
            a.remove(self)

But, because of circular references, we need to use weak refs on at least 
half of the equations. However, I want the B to destroy itself even when 
there is one or more A's pointing to it. So I will implement weakrefs on 
both sides.

# With weakrefs...
class A:
    def __init__(self):V
        self.has = []

    def add(self, b):
        if b not in self.has:
            self.has.append(weakref.ref(b))

    def remove(self, b):
        self.has.remove(b)

    def __del__(self):
        for b in self.has:
            b().removedfrom(self)

            
class B:
    def __init__(self):
        self.hadby = []

    def addedby(self, a):
        self.hadby.append(weakref.ref(a))

    def removedfrom(self, a):
        self.hadby.remove(a)

    def __del__(self):
        for a in self.hadby:
            a().remove(self)

Question 1: Is this the way it should be done?

Question 2: "if b in self.has:" will not ever return true because:
>>>  a = Something()
>>> b = a
>>> c = weakref.ref(a)
>>> b is a
1
>>> c is a
0
>>> c() is a
1

-- 
Jonathan Gardner
"Infinity isn't all that large - except at the end." -- Uncle Al

Please don't take anything I say seriously, even if you are really gullible.



More information about the Python-list mailing list