PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 2ms app.codeStats 1ms

/django/dispatch/saferef.py

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