2008-08-06 23:32:46 +08:00
|
|
|
"""
|
|
|
|
"Safe weakrefs", originally from pyDispatcher.
|
|
|
|
|
|
|
|
Provides a way to safely weakref any function, including bound methods (which
|
|
|
|
aren't handled by the core weakref module).
|
|
|
|
"""
|
|
|
|
|
2011-07-13 17:35:51 +08:00
|
|
|
import traceback
|
|
|
|
import weakref
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-11-03 17:22:11 +08:00
|
|
|
def safeRef(target, onDelete=None):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""Return a *safe* weak reference to a callable target
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
target -- the object to be weakly referenced, if it's a
|
|
|
|
bound method reference, will create a BoundMethodWeakref,
|
|
|
|
otherwise creates a simple weakref.
|
|
|
|
onDelete -- if provided, will have a hard reference stored
|
|
|
|
to the callable to be called after the safe reference
|
|
|
|
goes out of scope with the reference object, (either a
|
|
|
|
weakref or a BoundMethodWeakref) as argument.
|
|
|
|
"""
|
2012-05-13 04:32:43 +08:00
|
|
|
if hasattr(target, '__self__'):
|
|
|
|
if target.__self__ is not None:
|
2006-07-22 04:48:17 +08:00
|
|
|
# Turn a bound method into a BoundMethodWeakref instance.
|
|
|
|
# Keep track of these instances for lookup by disconnect().
|
2013-10-11 19:25:14 +08:00
|
|
|
assert hasattr(target, '__func__'), """safeRef target %r has __self__, but no __func__, don't know how to create reference""" % (target,)
|
2007-10-22 02:26:24 +08:00
|
|
|
reference = get_bound_method_weakref(
|
2006-07-22 04:48:17 +08:00
|
|
|
target=target,
|
|
|
|
onDelete=onDelete
|
|
|
|
)
|
|
|
|
return reference
|
|
|
|
if callable(onDelete):
|
|
|
|
return weakref.ref(target, onDelete)
|
|
|
|
else:
|
2013-10-15 03:13:14 +08:00
|
|
|
return weakref.ref(target)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class BoundMethodWeakref(object):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""'Safe' and reusable weak references to instance methods
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
BoundMethodWeakref objects provide a mechanism for
|
|
|
|
referencing a bound method without requiring that the
|
|
|
|
method object itself (which is normally a transient
|
|
|
|
object) is kept alive. Instead, the BoundMethodWeakref
|
|
|
|
object keeps weak references to both the object and the
|
|
|
|
function which together define the instance method.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
Attributes:
|
|
|
|
key -- the identity key for the reference, calculated
|
|
|
|
by the class's calculateKey method applied to the
|
|
|
|
target instance method
|
|
|
|
deletionMethods -- sequence of callable objects taking
|
|
|
|
single argument, a reference to this object which
|
|
|
|
will be called when *either* the target object or
|
|
|
|
target function is garbage collected (i.e. when
|
|
|
|
this object becomes invalid). These are specified
|
|
|
|
as the onDelete parameters of safeRef calls.
|
|
|
|
weakSelf -- weak reference to the target object
|
|
|
|
weakFunc -- weak reference to the target function
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
Class Attributes:
|
|
|
|
_allInstances -- class attribute pointing to all live
|
|
|
|
BoundMethodWeakref objects indexed by the class's
|
|
|
|
calculateKey(target) method applied to the target
|
|
|
|
objects. This weak value dictionary is used to
|
|
|
|
short-circuit creation so that multiple references
|
|
|
|
to the same (object, function) pair produce the
|
|
|
|
same BoundMethodWeakref instance.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
"""
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
_allInstances = weakref.WeakValueDictionary()
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2013-10-25 01:30:03 +08:00
|
|
|
def __new__(cls, target, onDelete=None, *arguments, **named):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""Create new instance or return current instance
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
Basically this method of construction allows us to
|
|
|
|
short-circuit creation of references to already-
|
|
|
|
referenced instance methods. The key corresponding
|
|
|
|
to the target is calculated, and if there is already
|
|
|
|
an existing reference, that is returned, with its
|
|
|
|
deletionMethods attribute updated. Otherwise the
|
|
|
|
new instance is created and registered in the table
|
|
|
|
of already-referenced methods.
|
|
|
|
"""
|
|
|
|
key = cls.calculateKey(target)
|
2013-10-23 18:09:29 +08:00
|
|
|
current = cls._allInstances.get(key)
|
2006-07-22 04:48:17 +08:00
|
|
|
if current is not None:
|
2013-10-15 03:13:14 +08:00
|
|
|
current.deletionMethods.append(onDelete)
|
2006-07-22 04:48:17 +08:00
|
|
|
return current
|
|
|
|
else:
|
2013-10-15 03:13:14 +08:00
|
|
|
base = super(BoundMethodWeakref, cls).__new__(cls)
|
2006-07-22 04:48:17 +08:00
|
|
|
cls._allInstances[key] = base
|
2013-10-27 01:50:40 +08:00
|
|
|
base.__init__(target, onDelete, *arguments, **named)
|
2006-07-22 04:48:17 +08:00
|
|
|
return base
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
def __init__(self, target, onDelete=None):
|
|
|
|
"""Return a weak-reference-like instance for a bound method
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
target -- the instance-method target for the weak
|
2012-05-13 04:32:43 +08:00
|
|
|
reference, must have __self__ and __func__ attributes
|
2006-07-22 04:48:17 +08:00
|
|
|
and be reconstructable via:
|
2012-05-13 04:32:43 +08:00
|
|
|
target.__func__.__get__( target.__self__ )
|
2006-07-22 04:48:17 +08:00
|
|
|
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 remove(weak, self=self):
|
|
|
|
"""Set self.isDead to true when method or instance is destroyed"""
|
|
|
|
methods = self.deletionMethods[:]
|
|
|
|
del self.deletionMethods[:]
|
|
|
|
try:
|
2013-10-15 03:13:14 +08:00
|
|
|
del self.__class__._allInstances[self.key]
|
2006-07-22 04:48:17 +08:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
for function in methods:
|
|
|
|
try:
|
2013-10-15 03:13:14 +08:00
|
|
|
if callable(function):
|
|
|
|
function(self)
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
2006-07-22 04:48:17 +08:00
|
|
|
try:
|
|
|
|
traceback.print_exc()
|
2012-04-29 00:02:01 +08:00
|
|
|
except AttributeError:
|
|
|
|
print('Exception during saferef %s cleanup function %s: %s' % (
|
|
|
|
self, function, e)
|
2006-07-22 04:48:17 +08:00
|
|
|
)
|
|
|
|
self.deletionMethods = [onDelete]
|
2013-10-15 03:13:14 +08:00
|
|
|
self.key = self.calculateKey(target)
|
2012-05-13 04:32:43 +08:00
|
|
|
self.weakSelf = weakref.ref(target.__self__, remove)
|
|
|
|
self.weakFunc = weakref.ref(target.__func__, remove)
|
|
|
|
self.selfName = str(target.__self__)
|
|
|
|
self.funcName = str(target.__func__.__name__)
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2013-11-20 10:02:30 +08:00
|
|
|
@classmethod
|
2013-10-15 03:13:14 +08:00
|
|
|
def calculateKey(cls, target):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""Calculate the reference key for this reference
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
Currently this is a two-tuple of the id()'s of the
|
|
|
|
target object and the target function respectively.
|
|
|
|
"""
|
2013-10-27 01:50:40 +08:00
|
|
|
return (id(target.__self__), id(target.__func__))
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
def __str__(self):
|
|
|
|
"""Give a friendly representation of the object"""
|
2013-10-11 19:25:14 +08:00
|
|
|
return """%s( %s.%s )""" % (
|
2006-07-22 04:48:17 +08:00
|
|
|
self.__class__.__name__,
|
|
|
|
self.selfName,
|
|
|
|
self.funcName,
|
|
|
|
)
|
2012-08-16 00:19:21 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
__repr__ = __str__
|
2012-08-16 00:19:21 +08:00
|
|
|
|
2013-02-26 05:53:08 +08:00
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.key)
|
2012-08-16 00:19:21 +08:00
|
|
|
|
2013-10-15 03:13:14 +08:00
|
|
|
def __bool__(self):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""Whether we are still a valid reference"""
|
|
|
|
return self() is not None
|
2012-11-04 04:43:11 +08:00
|
|
|
|
|
|
|
def __nonzero__(self): # Python 2 compatibility
|
|
|
|
return type(self).__bool__(self)
|
2012-05-18 20:52:24 +08:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
2006-07-22 04:48:17 +08:00
|
|
|
"""Compare with another reference"""
|
2012-05-18 20:52:24 +08:00
|
|
|
if not isinstance(other, self.__class__):
|
|
|
|
return self.__class__ == type(other)
|
|
|
|
return self.key == other.key
|
2012-11-04 04:43:11 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
def __call__(self):
|
|
|
|
"""Return a strong reference to the bound method
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
If the target cannot be retrieved, then will
|
|
|
|
return None, otherwise returns a bound instance
|
|
|
|
method for our object and function.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-07-22 04:48:17 +08:00
|
|
|
Note:
|
|
|
|
You may call this method any number of times,
|
|
|
|
as it does not invalidate the reference.
|
|
|
|
"""
|
|
|
|
target = self.weakSelf()
|
|
|
|
if target is not None:
|
|
|
|
function = self.weakFunc()
|
|
|
|
if function is not None:
|
|
|
|
return function.__get__(target)
|
|
|
|
return None
|
2007-10-22 02:26:24 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-10-22 02:26:24 +08:00
|
|
|
class BoundNonDescriptorMethodWeakref(BoundMethodWeakref):
|
|
|
|
"""A specialized BoundMethodWeakref, for platforms where instance methods
|
|
|
|
are not descriptors.
|
|
|
|
|
|
|
|
It assumes that the function name and the target attribute name are the
|
|
|
|
same, instead of assuming that the function is a descriptor. This approach
|
|
|
|
is equally fast, but not 100% reliable because functions can be stored on an
|
|
|
|
attribute named differenty than the function's name such as in:
|
|
|
|
|
|
|
|
class A: pass
|
|
|
|
def foo(self): return "foo"
|
|
|
|
A.bar = foo
|
|
|
|
|
|
|
|
But this shouldn't be a common use case. So, on platforms where methods
|
|
|
|
aren't descriptors (such as Jython) this implementation has the advantage
|
|
|
|
of working in the most cases.
|
|
|
|
"""
|
|
|
|
def __init__(self, target, onDelete=None):
|
|
|
|
"""Return a weak-reference-like instance for a bound method
|
|
|
|
|
|
|
|
target -- the instance-method target for the weak
|
2012-05-13 04:32:43 +08:00
|
|
|
reference, must have __self__ and __func__ attributes
|
2007-10-22 02:26:24 +08:00
|
|
|
and be reconstructable via:
|
2012-05-13 04:32:43 +08:00
|
|
|
target.__func__.__get__( target.__self__ )
|
2007-10-22 02:26:24 +08:00
|
|
|
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.
|
|
|
|
"""
|
2012-05-13 04:32:43 +08:00
|
|
|
assert getattr(target.__self__, target.__name__) == target, \
|
2007-10-22 02:26:24 +08:00
|
|
|
("method %s isn't available as the attribute %s of %s" %
|
2012-05-13 04:32:43 +08:00
|
|
|
(target, target.__name__, target.__self__))
|
2007-10-22 02:26:24 +08:00
|
|
|
super(BoundNonDescriptorMethodWeakref, self).__init__(target, onDelete)
|
|
|
|
|
|
|
|
def __call__(self):
|
|
|
|
"""Return a strong reference to the bound method
|
|
|
|
|
|
|
|
If the target cannot be retrieved, then will
|
|
|
|
return None, otherwise returns a bound instance
|
|
|
|
method for our object and function.
|
|
|
|
|
|
|
|
Note:
|
|
|
|
You may call this method any number of times,
|
|
|
|
as it does not invalidate the reference.
|
|
|
|
"""
|
|
|
|
target = self.weakSelf()
|
|
|
|
if target is not None:
|
|
|
|
function = self.weakFunc()
|
|
|
|
if function is not None:
|
2011-03-28 10:11:19 +08:00
|
|
|
# Using partial() would be another option, but it erases the
|
2007-10-22 02:26:24 +08:00
|
|
|
# "signature" of the function. That is, after a function is
|
|
|
|
# curried, the inspect module can't be used to determine how
|
|
|
|
# many arguments the function expects, nor what keyword
|
|
|
|
# arguments it supports, and pydispatcher needs this
|
|
|
|
# information.
|
|
|
|
return getattr(target, function.__name__)
|
|
|
|
return None
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-10-22 02:26:24 +08:00
|
|
|
def get_bound_method_weakref(target, onDelete):
|
|
|
|
"""Instantiates the appropiate BoundMethodWeakRef, depending on the details of
|
|
|
|
the underlying class method implementation"""
|
|
|
|
if hasattr(target, '__get__'):
|
|
|
|
# target method is a descriptor, so the default implementation works:
|
|
|
|
return BoundMethodWeakref(target=target, onDelete=onDelete)
|
|
|
|
else:
|
|
|
|
# no luck, use the alternative implementation:
|
|
|
|
return BoundNonDescriptorMethodWeakref(target=target, onDelete=onDelete)
|