saferef.py 7.5 KB

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