July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Joseph A. Knapka
You want to hold bound methods, while still allowing the associated object to be garbage-collected.
Weak
references were an important addition to Python 2.1, but
they’re not directly usable for bound methods,
unless you take some precautions. To allow an object to be
garbage-collected despite outstanding references to its bound
methods, you need some wrappers. Put the following in the
weakmethod.py file:
import weakref
class _weak_callable:
def _ _init_ _(self, obj, func):
self.im_self = obj
self.im_func = func
def _ _call_ _(self, *args, **kws):
if self.im_self is None:
return self.im_func(*args, **kws)
else:
return self.im_func(self.im_self, *args, **kws)
class WeakMethod:
""" Wraps a function or, more importantly, a bound method in
a way that allows a bound method's object to be GCed, while
providing the same interface as a normal weak reference. """
def _ _init_ _(self, fn):
try:
self._obj = weakref.ref(fn.im_self)
self._meth = fn.im_func
except AttributeError:
# It's not a bound method
self._obj = None
self._meth = fn
def _ _call_ _(self):
if self._dead( ): return None
return _weak_callable(self._getobj( ), self._meth)
def _dead(self):
return self._obj is not None and self._obj( ) is None
def _getobj(self):
if self._obj is None: return None
return self._obj( )A normal bound method holds a strong reference to the bound method’s object. That means that the ...
Read now
Unlock full access