You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
7.2 KiB

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