Circular references (was: Defining VCL-like framework for Py
Gordon McMillan
gmcm at hypernet.com
Sat May 22 00:41:43 EDT 1999
I wrote:
[some code which doesn't do what it's supposed to]
This is stolen from some caching code, and it doesn't work very
well for weak references.
My caching code maintains it's own ref counts (because there may be
multiple references to a single object), and explicitly cleans out
the cache under certain conditions. I was kind of surprised it
"worked" as a demo, 'till I realized I had no circular ref!
This works, but only because it clears the cache:
d = {}
class proxy:
def __init__(self, obj):
self.__dict__['objid'] = id(obj)
d[self.objid] = obj
def __getattr__(self, nm):
return getattr(d[self.objid], nm)
def __setattr__(self, nm, value):
setattr(d[self.objid], nm, value)
def __del__(self, d=d):
try:
del d[self.objid]
except:
pass
class P:
def __init__(self):
self.children = []
def mthd(self):
for child in self.children:
child.mthd()
def __del__(self):
print "P deleted"
class C:
def mthd(self):
print "Hello from a C"
def __del__(self):
print "C deleted"
def test():
p = P()
c = C()
c.parent = p
p.children.append(proxy(c))
p.mthd()
test()
print "clearing cache"
d.clear()
print "That's all"
- Gordon
More information about the Python-list
mailing list