saferef.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """
  2. "Safe weakrefs", originally from pyDispatcher.
  3. Provides a way to safely weakref any function, including bound methods (which
  4. aren't handled by the core weakref module).
  5. """
  6. import weakref
  7. import traceback
  8. def safe_ref(target, on_delete=None):
  9. """Return a *safe* weak reference to a callable target
  10. :param target: the object to be weakly referenced, if it's a
  11. bound method reference, will create a :class:`BoundMethodWeakref`,
  12. otherwise creates a simple :class:`weakref.ref`.
  13. :keyword on_delete: if provided, will have a hard reference stored
  14. to the callable to be called after the safe reference
  15. goes out of scope with the reference object, (either a
  16. :class:`weakref.ref` or a :class:`BoundMethodWeakref`) as argument.
  17. """
  18. if getattr(target, "im_self", None) is not None:
  19. # Turn a bound method into a BoundMethodWeakref instance.
  20. # Keep track of these instances for lookup by disconnect().
  21. assert hasattr(target, 'im_func'), \
  22. """safe_ref target %r has im_self, but no im_func, " \
  23. "don't know how to create reference""" % (target, )
  24. return get_bound_method_weakref(target=target,
  25. on_delete=on_delete)
  26. if callable(on_delete):
  27. return weakref.ref(target, on_delete)
  28. else:
  29. return weakref.ref(target)
  30. class BoundMethodWeakref(object):
  31. """'Safe' and reusable weak references to instance methods.
  32. BoundMethodWeakref objects provide a mechanism for
  33. referencing a bound method without requiring that the
  34. method object itself (which is normally a transient
  35. object) is kept alive. Instead, the BoundMethodWeakref
  36. object keeps weak references to both the object and the
  37. function which together define the instance method.
  38. .. attribute:: key
  39. the identity key for the reference, calculated
  40. by the class's :meth:`calculate_key` method applied to the
  41. target instance method
  42. .. attribute:: deletion_methods
  43. sequence of callable objects taking
  44. single argument, a reference to this object which
  45. will be called when *either* the target object or
  46. target function is garbage collected (i.e. when
  47. this object becomes invalid). These are specified
  48. as the on_delete parameters of :func:`safe_ref` calls.
  49. .. attribute:: weak_self
  50. weak reference to the target object
  51. .. attribute:: weak_func
  52. weak reference to the target function
  53. .. attribute:: _all_instances
  54. class attribute pointing to all live
  55. BoundMethodWeakref objects indexed by the class's
  56. `calculate_key(target)` method applied to the target
  57. objects. This weak value dictionary is used to
  58. short-circuit creation so that multiple references
  59. to the same (object, function) pair produce the
  60. same BoundMethodWeakref instance.
  61. """
  62. _all_instances = weakref.WeakValueDictionary()
  63. def __new__(cls, target, on_delete=None, *arguments, **named):
  64. """Create new instance or return current instance
  65. Basically this method of construction allows us to
  66. short-circuit creation of references to already-
  67. referenced instance methods. The key corresponding
  68. to the target is calculated, and if there is already
  69. an existing reference, that is returned, with its
  70. deletionMethods attribute updated. Otherwise the
  71. new instance is created and registered in the table
  72. of already-referenced methods.
  73. """
  74. key = cls.calculate_key(target)
  75. current = cls._all_instances.get(key)
  76. if current is not None:
  77. current.deletion_methods.append(on_delete)
  78. return current
  79. else:
  80. base = super(BoundMethodWeakref, cls).__new__(cls)
  81. cls._all_instances[key] = base
  82. base.__init__(target, on_delete, *arguments, **named)
  83. return base
  84. def __init__(self, target, on_delete=None):
  85. """Return a weak-reference-like instance for a bound method
  86. :param target: the instance-method target for the weak
  87. reference, must have `im_self` and `im_func` attributes
  88. and be reconstructable via::
  89. target.im_func.__get__(target.im_self)
  90. which is true of built-in instance methods.
  91. :keyword on_delete: optional callback which will be called
  92. when this weak reference ceases to be valid
  93. (i.e. either the object or the function is garbage
  94. collected). Should take a single argument,
  95. which will be passed a pointer to this object.
  96. """
  97. def remove(weak, self=self):
  98. """Set self.is_dead to true when method or instance is destroyed"""
  99. methods = self.deletion_methods[:]
  100. del(self.deletion_methods[:])
  101. try:
  102. del(self.__class__._all_instances[self.key])
  103. except KeyError:
  104. pass
  105. for function in methods:
  106. try:
  107. if callable(function):
  108. function(self)
  109. except Exception, exc:
  110. try:
  111. traceback.print_exc()
  112. except AttributeError:
  113. print("Exception during saferef %s cleanup function "
  114. "%s: %s" % (self, function, exc))
  115. self.deletion_methods = [on_delete]
  116. self.key = self.calculate_key(target)
  117. self.weak_self = weakref.ref(target.im_self, remove)
  118. self.weak_func = weakref.ref(target.im_func, remove)
  119. self.self_name = str(target.im_self)
  120. self.func_name = str(target.im_func.__name__)
  121. def calculate_key(cls, target):
  122. """Calculate the reference key for this reference
  123. Currently this is a two-tuple of the `id()`'s of the
  124. target object and the target function respectively.
  125. """
  126. return id(target.im_self), id(target.im_func)
  127. calculate_key = classmethod(calculate_key)
  128. def __str__(self):
  129. """Give a friendly representation of the object"""
  130. return """%s( %s.%s )""" % (
  131. self.__class__.__name__,
  132. self.self_name,
  133. self.func_name,
  134. )
  135. __repr__ = __str__
  136. def __nonzero__(self):
  137. """Whether we are still a valid reference"""
  138. return self() is not None
  139. def __cmp__(self, other):
  140. """Compare with another reference"""
  141. if not isinstance(other, self.__class__):
  142. return cmp(self.__class__, type(other))
  143. return cmp(self.key, other.key)
  144. def __call__(self):
  145. """Return a strong reference to the bound method
  146. If the target cannot be retrieved, then will
  147. return None, otherwise returns a bound instance
  148. method for our object and function.
  149. Note:
  150. You may call this method any number of times,
  151. as it does not invalidate the reference.
  152. """
  153. target = self.weak_self()
  154. if target is not None:
  155. function = self.weak_func()
  156. if function is not None:
  157. return function.__get__(target)
  158. return None
  159. class BoundNonDescriptorMethodWeakref(BoundMethodWeakref):
  160. """A specialized :class:`BoundMethodWeakref`, for platforms where
  161. instance methods are not descriptors.
  162. It assumes that the function name and the target attribute name are the
  163. same, instead of assuming that the function is a descriptor. This approach
  164. is equally fast, but not 100% reliable because functions can be stored on
  165. an attribute named differenty than the function's name such as in::
  166. >>> class A(object):
  167. ... pass
  168. >>> def foo(self):
  169. ... return "foo"
  170. >>> A.bar = foo
  171. But this shouldn't be a common use case. So, on platforms where methods
  172. aren't descriptors (such as Jython) this implementation has the advantage
  173. of working in the most cases.
  174. """
  175. def __init__(self, target, on_delete=None):
  176. """Return a weak-reference-like instance for a bound method
  177. :param target: the instance-method target for the weak
  178. reference, must have `im_self` and `im_func` attributes
  179. and be reconstructable via::
  180. target.im_func.__get__(target.im_self)
  181. which is true of built-in instance methods.
  182. :keyword on_delete: optional callback which will be called
  183. when this weak reference ceases to be valid
  184. (i.e. either the object or the function is garbage
  185. collected). Should take a single argument,
  186. which will be passed a pointer to this object.
  187. """
  188. assert getattr(target.im_self, target.__name__) == target, \
  189. "method %s isn't available as the attribute %s of %s" % (
  190. target, target.__name__, target.im_self)
  191. super(BoundNonDescriptorMethodWeakref, self).__init__(target,
  192. on_delete)
  193. def __call__(self):
  194. """Return a strong reference to the bound method
  195. If the target cannot be retrieved, then will
  196. return None, otherwise returns a bound instance
  197. method for our object and function.
  198. Note:
  199. You may call this method any number of times,
  200. as it does not invalidate the reference.
  201. """
  202. target = self.weak_self()
  203. if target is not None:
  204. function = self.weak_func()
  205. if function is not None:
  206. # Using curry() would be another option, but it erases the
  207. # "signature" of the function. That is, after a function is
  208. # curried, the inspect module can't be used to determine how
  209. # many arguments the function expects, nor what keyword
  210. # arguments it supports, and pydispatcher needs this
  211. # information.
  212. return getattr(target, function.__name__)
  213. return None
  214. def get_bound_method_weakref(target, on_delete):
  215. """Instantiates the appropiate :class:`BoundMethodWeakRef`, depending
  216. on the details of the underlying class method implementation."""
  217. if hasattr(target, '__get__'):
  218. # target method is a descriptor, so the default implementation works:
  219. return BoundMethodWeakref(target=target, on_delete=on_delete)
  220. else:
  221. # no luck, use the alternative implementation:
  222. return BoundNonDescriptorMethodWeakref(target=target,
  223. on_delete=on_delete)