signal.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. Created on Mon Mar 11 18:39:13 2013
  3. @author Vaclav Petras <wenzeslaus gmail.com>
  4. """
  5. from grass.pydispatch import dispatcher
  6. def _islambda(function):
  7. """
  8. Tests if object is a lambda function.
  9. Should work on the most of Python implementations where name of lambda
  10. function is not unique.
  11. >>> mylambda = lambda x: x*x
  12. >>> _islambda(mylambda)
  13. True
  14. >>> _islambda(_islambda)
  15. False
  16. """
  17. return (
  18. isinstance(function, type(lambda: None))
  19. and function.__name__ == (lambda: None).__name__
  20. )
  21. class Signal(object):
  22. """
  23. The signal object is created usually as a instance attribute.
  24. However, it can be created anywhere.
  25. >>> signal1 = Signal('signal1')
  26. The function has to be connected to a signal in order to be called when
  27. the signal is emitted. The connection can be done where the function is
  28. defined (e. g., a class) but also on some other place, typically,
  29. user of a class connects some signal to the method of some other class.
  30. >>> def handler1():
  31. ... print "from handler1"
  32. >>> signal1.connect(handler1)
  33. Emitting of the signal is done usually only in the class which has the
  34. signal as a instance attribute. Again, generally, it can be emitted
  35. anywhere.
  36. >>> signal1.emit()
  37. from handler1
  38. The signal can have parameters. These parameters are specified when
  39. emitting but should be documented together with the signal (e.g., in the
  40. class documentation). Parameters should be keyword arguments and handlers
  41. must use these names (if the names cannot be the same, lambda function
  42. can be used to overcome this problem).
  43. >>> signal2 = Signal('signal2')
  44. >>> def handler2(text):
  45. ... print "handler2: %s" % text
  46. >>> signal2.connect(handler2)
  47. >>> signal2.emit(text="Hello")
  48. handler2: Hello
  49. Do not emit the same signal with different parameters when emitting at
  50. different places.
  51. A handler is the standard function, lambda function, method or any other
  52. callable object.
  53. >>> import sys
  54. >>> signal2.connect(lambda text:
  55. ... sys.stdout.write('lambda handler: %s\\n' % text))
  56. >>> signal2.emit(text="Hi")
  57. handler2: Hi
  58. lambda handler: Hi
  59. The handler function can have only some of the signal parameters or no
  60. parameters at all even if the signal has some.
  61. >>> def handler3():
  62. ... print "from handler3"
  63. >>> signal2.connect(handler3)
  64. >>> signal2.emit(text="Ciao")
  65. handler2: Ciao
  66. lambda handler: Ciao
  67. from handler3
  68. It is possible to use signal as a handler. By this, signals can be
  69. forwarded from one object to another. In other words, one object can
  70. expose signal of some object.
  71. >>> signal3 = Signal('signal3')
  72. >>> signal3.connect(handler3)
  73. >>> signal1.connect(signal3)
  74. >>> signal1.emit()
  75. from handler1
  76. from handler3
  77. It is possible to disconnect a particular handler.
  78. >>> signal3.disconnect(handler3)
  79. >>> signal1.emit()
  80. from handler1
  81. >>> signal2.disconnect(handler2)
  82. >>> signal2.disconnect(handler3)
  83. >>> signal2.emit(text='Hello')
  84. lambda handler: Hello
  85. """
  86. # TODO: use the name for debugging
  87. def __init__(self, name):
  88. """Creates a signal object.
  89. The parameter name is used for debugging.
  90. """
  91. self._name = name
  92. def connect(self, handler, weak=None):
  93. """
  94. Connects handler to a signal.
  95. Typically, a signal is defined in some class and the user of this
  96. class connects to the signal::
  97. from module import SomeClass
  98. ...
  99. self.someObject = SomeClass()
  100. self.someObject.connect(self.someMethod)
  101. Usually, it is not needed to set the weak parameter. This method
  102. creates weak references for all handlers but for lambda functions, it
  103. automatically creates (standard) references (otherwise, lambdas would be
  104. garbage collected. If you want to force some behaviour, specify the
  105. weak parameter.
  106. >>> signal1 = Signal('signal1')
  107. >>> import sys
  108. >>> signal1.connect(lambda: sys.stdout.write('will print\\n'))
  109. >>> signal1.connect(lambda: sys.stdout.write('will print\\n'), weak=False)
  110. >>> signal1.connect(lambda: sys.stdout.write('will not print'), weak=True)
  111. >>> signal1.emit()
  112. will print
  113. will print
  114. """
  115. if weak is None:
  116. if _islambda(handler):
  117. weak = False
  118. else:
  119. weak = True
  120. dispatcher.connect(receiver=handler, signal=self, weak=weak)
  121. def disconnect(self, handler, weak=True):
  122. """
  123. Disconnects a specified handler.
  124. It is not necessary to disconnect object when it is deleted.
  125. Underlying PyDispatcher will take care of connections to deleted
  126. objects.
  127. >>> signal1 = Signal('signal1')
  128. >>> import sys
  129. >>> signal1.connect(sys.stdout.write)
  130. >>> signal1.disconnect(sys.stdout.write)
  131. The weak parameter of must have the same value as for connection.
  132. If you not specified the parameter when connecting,
  133. you don't have to specify it when disconnecting.
  134. Disconnecting the not-connected handler will result in error.
  135. >>> signal1.disconnect(sys.stdout.flush) #doctest: +ELLIPSIS
  136. Traceback (most recent call last):
  137. DispatcherKeyError: 'No receivers found for signal ...'
  138. Disconnecting the non-exiting or unknown handler will result in error.
  139. >>> signal1.disconnect(some_function)
  140. Traceback (most recent call last):
  141. NameError: name 'some_function' is not defined
  142. >>> signal1.emit()
  143. """
  144. dispatcher.disconnect(receiver=handler, signal=self, weak=weak)
  145. # TODO: remove args?, make it work for args?
  146. # TODO: where to put documentation
  147. def emit(self, *args, **kwargs):
  148. """
  149. Emits the signal which means that all connected handlers will be
  150. called.
  151. It is advised to have signals as instance attributes and emit signals
  152. only in the class which owns the signal::
  153. class Abc(object):
  154. def __init__(self):
  155. self.colorChanged = Signal('Abc.colorChanged')
  156. ...
  157. def setColor(self, color):
  158. ...
  159. self.colorChanged.emit(oldColor=self.Color, newColor=color)
  160. ...
  161. Documentation of an signal should be placed to the class documentation
  162. or to the code (this need to be more specified).
  163. Calling a signal from outside the class is usually not good
  164. practice. The only case when it is permitted is when signal is the part
  165. of some globaly shared object and permission to emit is stayed in the
  166. documentation.
  167. The parameters of the emit function must be the same as the parameters
  168. of the handlers. However, handler can omit some parameters.
  169. The associated parameters shall be documented for each Signal instance.
  170. Use only keyword arguments when emitting.
  171. >>> signal1 = Signal('signal1')
  172. >>> def mywrite(text):
  173. ... print text
  174. >>> signal1.connect(mywrite)
  175. >>> signal1.emit(text='Hello')
  176. Hello
  177. >>> signal1.emit()
  178. Traceback (most recent call last):
  179. TypeError: mywrite() takes exactly 1 argument (0 given)
  180. >>> signal1.emit('Hello')
  181. Traceback (most recent call last):
  182. TypeError: send() got multiple values for keyword argument 'signal'
  183. """
  184. dispatcher.send(signal=self, *args, **kwargs)
  185. # TODO: remove args?
  186. def __call__(self, *args, **kwargs):
  187. """Allows emitting signal with function call syntax.
  188. It allows handling signal as a function or other callable object.
  189. So, the signal can be in the list of functions or can be connected as
  190. a handler for another signal.
  191. However, it is strongly recommended to use emit method for direct
  192. signal emitting.
  193. The use of emit method is more explicit than the function call
  194. and thus it it clear that we are using signal.
  195. >>> signal1 = Signal('signal1')
  196. >>> def mywrite(text):
  197. ... print text
  198. >>> signal1.connect(mywrite)
  199. >>> functions = [signal1, lambda text: mywrite(text + '!')]
  200. >>> for function in functions:
  201. ... function(text='text')
  202. text
  203. text!
  204. The other reason why the function call should not by used when it is
  205. possible to use emit method is that this function does ugly hack to
  206. enable calling as a signal handler. The signal parameter is deleted
  207. when it is in named keyword arguments. As a consequence, when the
  208. signal is emitted with the signal parameter (which is a very bad
  209. name for parameter when using signals), the error is much more readable
  210. when using emit than function call. Concluding remark is that
  211. emit behaves more predictable.
  212. >>> signal1.emit(signal='Hello')
  213. Traceback (most recent call last):
  214. TypeError: send() got multiple values for keyword argument 'signal'
  215. >>> signal1(signal='Hello')
  216. Traceback (most recent call last):
  217. TypeError: mywrite() takes exactly 1 argument (0 given)
  218. """
  219. if "signal" in kwargs:
  220. del kwargs["signal"]
  221. self.emit(*args, **kwargs)
  222. if __name__ == "__main__":
  223. import doctest
  224. doctest.testmod()