saferef.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Refactored "safe reference" from dispatcher.py"""
  2. from __future__ import print_function
  3. import weakref
  4. import traceback
  5. import sys
  6. if sys.hexversion >= 0x3000000:
  7. im_func = "__func__"
  8. im_self = "__self__"
  9. else:
  10. im_func = "im_func"
  11. im_self = "im_self"
  12. def safeRef(target, onDelete=None):
  13. """Return a *safe* weak reference to a callable target
  14. target -- the object to be weakly referenced, if it's a
  15. bound method reference, will create a BoundMethodWeakref,
  16. otherwise creates a simple weakref.
  17. onDelete -- if provided, will have a hard reference stored
  18. to the callable to be called after the safe reference
  19. goes out of scope with the reference object, (either a
  20. weakref or a BoundMethodWeakref) as argument.
  21. """
  22. if hasattr(target, im_self):
  23. if getattr(target, im_self) is not None:
  24. # Turn a bound method into a BoundMethodWeakref instance.
  25. # Keep track of these instances for lookup by disconnect().
  26. assert hasattr(target, im_func), (
  27. """safeRef target %r has %s, """
  28. """but no %s, don't know how """
  29. """to create reference""" % (target, im_self, im_func)
  30. )
  31. reference = BoundMethodWeakref(target=target, onDelete=onDelete)
  32. return reference
  33. if onDelete is not None:
  34. return weakref.ref(target, onDelete)
  35. else:
  36. return weakref.ref(target)
  37. class BoundMethodWeakref(object):
  38. """'Safe' and reusable weak references to instance methods
  39. BoundMethodWeakref objects provide a mechanism for
  40. referencing a bound method without requiring that the
  41. method object itself (which is normally a transient
  42. object) is kept alive. Instead, the BoundMethodWeakref
  43. object keeps weak references to both the object and the
  44. function which together define the instance method.
  45. Attributes:
  46. key -- the identity key for the reference, calculated
  47. by the class's calculateKey method applied to the
  48. target instance method
  49. deletionMethods -- sequence of callable objects taking
  50. single argument, a reference to this object which
  51. will be called when *either* the target object or
  52. target function is garbage collected (i.e. when
  53. this object becomes invalid). These are specified
  54. as the onDelete parameters of safeRef calls.
  55. weakSelf -- weak reference to the target object
  56. weakFunc -- weak reference to the target function
  57. Class Attributes:
  58. _allInstances -- class attribute pointing to all live
  59. BoundMethodWeakref objects indexed by the class's
  60. calculateKey(target) method applied to the target
  61. objects. This weak value dictionary is used to
  62. short-circuit creation so that multiple references
  63. to the same (object, function) pair produce the
  64. same BoundMethodWeakref instance.
  65. """
  66. _allInstances = weakref.WeakValueDictionary()
  67. def __new__(cls, target, onDelete=None, *arguments, **named):
  68. """Create new instance or return current instance
  69. Basically this method of construction allows us to
  70. short-circuit creation of references to already-
  71. referenced instance methods. The key corresponding
  72. to the target is calculated, and if there is already
  73. an existing reference, that is returned, with its
  74. deletionMethods attribute updated. Otherwise the
  75. new instance is created and registered in the table
  76. of already-referenced methods.
  77. """
  78. key = cls.calculateKey(target)
  79. current = cls._allInstances.get(key)
  80. if current is not None:
  81. current.deletionMethods.append(onDelete)
  82. return current
  83. else:
  84. base = super(BoundMethodWeakref, cls).__new__(cls)
  85. cls._allInstances[key] = base
  86. base.__init__(target, onDelete, *arguments, **named)
  87. return base
  88. def __init__(self, target, onDelete=None):
  89. """Return a weak-reference-like instance for a bound method
  90. target -- the instance-method target for the weak
  91. reference, must have <im_self> and <im_func> attributes
  92. and be reconstructable via:
  93. target.<im_func>.__get__( target.<im_self> )
  94. which is true of built-in instance methods.
  95. onDelete -- optional callback which will be called
  96. when this weak reference ceases to be valid
  97. (i.e. either the object or the function is garbage
  98. collected). Should take a single argument,
  99. which will be passed a pointer to this object.
  100. """
  101. def remove(weak, self=self):
  102. """Set self.isDead to true when method or instance is destroyed"""
  103. methods = self.deletionMethods[:]
  104. del self.deletionMethods[:]
  105. try:
  106. del self.__class__._allInstances[self.key]
  107. except KeyError:
  108. pass
  109. for function in methods:
  110. try:
  111. if hasattr(function, "__call__"):
  112. function(self)
  113. except Exception as e:
  114. try:
  115. traceback.print_exc()
  116. except AttributeError:
  117. print(
  118. """Exception during saferef %s cleanup """
  119. """function %s: %s""" % (self, function, e),
  120. file=sys.stderr,
  121. )
  122. self.deletionMethods = [onDelete]
  123. self.key = self.calculateKey(target)
  124. self.weakSelf = weakref.ref(getattr(target, im_self), remove)
  125. self.weakFunc = weakref.ref(getattr(target, im_func), remove)
  126. self.selfName = getattr(target, im_self).__class__.__name__
  127. self.funcName = str(getattr(target, im_func).__name__)
  128. def calculateKey(cls, target):
  129. """Calculate the reference key for this reference
  130. Currently this is a two-tuple of the id()'s of the
  131. target object and the target function respectively.
  132. """
  133. return (id(getattr(target, im_self)), id(getattr(target, im_func)))
  134. calculateKey = classmethod(calculateKey)
  135. def __str__(self):
  136. """Give a friendly representation of the object"""
  137. return """%s( %s.%s )""" % (
  138. self.__class__.__name__,
  139. self.selfName,
  140. self.funcName,
  141. )
  142. __repr__ = __str__
  143. def __nonzero__(self):
  144. """Whether we are still a valid reference"""
  145. return self() is not None
  146. def __cmp__(self, other):
  147. """Compare with another reference"""
  148. if not isinstance(other, self.__class__):
  149. return cmp(self.__class__, type(other))
  150. return cmp(self.key, other.key)
  151. def __call__(self):
  152. """Return a strong reference to the bound method
  153. If the target cannot be retrieved, then will
  154. return None, otherwise returns a bound instance
  155. method for our object and function.
  156. Note:
  157. You may call this method any number of times,
  158. as it does not invalidate the reference.
  159. """
  160. target = self.weakSelf()
  161. if target is not None:
  162. function = self.weakFunc()
  163. if function is not None:
  164. return function.__get__(target)
  165. return None