saferef.py 7.5 KB

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