I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.
- Do you have any thoughts on my code?
- Do you think I handle errors appropriately?
- Is it missing anything?
- What should be done to make it more robust?
- Is the documentation clear enough?
import weakref
class WeakBoundMethod:
"""
Wrapper around a method bound to a class instance. As opposed to bare
bound methods, it holds only a weak reference to the `self` object,
allowing it to be deleted.
This can be useful when implementing certain kinds of systems that
manage callback functions, such as an event manager.
"""
def __init__(self, meth):
"""
Initializes the class instance. It should be ensured that methods
passed through the `meth` parameter are always bound methods. Static
methods and free functions will produce an `AssertionError`.
"""
assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
'Object is not a bound method.'
self._self = weakref.ref(meth.__self__)
self._func = meth.__func__
def __call__(self, *args, **kw):
"""
Calls the bound method and returns whatever object the method returns.
Any arguments passed to this will also be forwarded to the method.
In case an exception is raised by the bound method, it will be
caught and thrown again to the caller of this `WeakBoundMethod` object.
Calling this on objects that have been collected will result in
an `AssertionError` being raised.
"""
assert self.alive(), 'Bound method called on deleted object.'
try:
return self._func(self._self(), *args, **kw)
except Exception, e:
raise e
def alive(self):
"""
Checks whether the `self` object the method is bound to has
been collected.
"""
return self._self() is not None