'Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be called
when this weak reference ceases to be valid
(i.e. either the object or the function is garbage
collected).  Should take a single argument,
which will be passed a pointer to this object.'

def __init__(self, target, onDelete=None):

    def remove(weak, self=self):
        'Set    self.isDead    to    true    when    method    or    instance    is    destroyed'
        methods = self.deletionMethods[:]
        del self.deletionMethods[:]
        try:
            del self.__class__._allInstances[self.key]
        except KeyError:
            pass
        for function in methods:
            try:
                if callable(function):
                    function(self)
            except Exception as e:
                try:
                    traceback.print_exc()
                except AttributeError as err:
                    print ('Exception    during    saferef    %s    cleanup    function    %s:    %s' % (self, function, e))
    self.deletionMethods = [onDelete]
    self.key = self.calculateKey(target)
    self.weakSelf = weakref.ref(target.im_self, remove)
    self.weakFunc = weakref.ref(target.im_func, remove)
    self.selfName = str(target.im_self)
    self.funcName = str(target.im_func.__name__)
