signal.py 9.5 KB

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