[Michael Bayer]
> why not encapsulate the "proper" weakref-based approach in an easy-to-
> use method such as "__close__()" ? that way nobody has to guess how
> to follow this pattern.
An encapsulating function should be added to the weakref module
so that Guido's example could be written as:
class BufferedWriter:
def __init__(self, raw):
self.raw = raw
self.buffer = ""
weakref.cleanup(self, lambda s: s.raw.write(s.buffer))
def write(self, data):
self.buffer += data
if len(self.buffer) >= 8192:
self.flush()
def flush(self):
self.raw.write(self.buffer)
self.buffer = ""
I've got a first cut at an encapsulating function but am not happy with it yet.
There is almost certainly a better way. First draft:
def cleanup(obj, callback, _reg = []):
class AttrMap(object):
def __init__(self, map):
self._map = map
def __getattr__(self, key):
return self._map[key]
def wrapper(wr, mp=AttrMap(obj.__dict__), callback=callback):
_reg.remove(wr)
callback(mp)
_reg.append(ref(obj, wrapper))
Raymond
_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe:
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com