Guest User

Untitled

a guest
Feb 18th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. """
  2. A DIRT simple message bus
  3. Rules for usage
  4. To prevent the application turning into a programmatic
  5. snakes and ladders or call spaghetti... Receiver should be named
  6. like moduleName.className or moduleName.defName atleast making it
  7. visibly understandable that
  8. bus.all("foo.ProcessThis") is generally going to be going to an instance
  9. of foo.ProcessThis where foo has been instantiated in main.py or some other
  10. central startup point. Still not perfect but meh
  11. """
  12. from collections import defaultdict
  13. channels = defaultdict(list)
  14.  
  15. def registerSingle(name, callback):
  16. """
  17. Similar to register but ensures only one callback is register to a channel
  18. @todo change Exception to something more appropriate
  19.  
  20. :name str A reasonably coherent name for a callback channel
  21. :callback callable Either a bound method or just a function
  22. """
  23. global channels
  24. if count(channels[name]) > 0:
  25. raise Exception("Tried to register %s but already has %s registered" % ( name, channels) )
  26. channels[name].append(callback)
  27.  
  28. def register(name, callback):
  29. """
  30. Binds a callback to a named channel
  31.  
  32. :name str A reasonably coherent name for a callback channel
  33. :callback callable Either a bound method or just a function
  34. """
  35. global channels
  36. channels[name].append(callback)
  37.  
  38.  
  39. def call(name, *args, **kwargs):
  40. """
  41. Applies the provided arguments to any and all callbacks for a specified channel
  42.  
  43. :name str A reasonably coherent name for a callback channel
  44. """
  45. for callback in channels[name]:
  46. callback(*args, **kwargs)
  47.  
  48. def first(name, default = lambda : False):
  49. """
  50. Returns the first callback for a chanel
  51.  
  52. :name str A reasonably coherent name for a callback channel
  53. :default To avoid exceptions and provided a fallback handler
  54. """
  55. return channels.get(name, default)
  56.  
  57. def all(name):
  58. """
  59. Generator to allow for finer grained control over the process of calling a channel
  60. handler
  61.  
  62. :name str A reasonably coherent name for a callback channel
  63.  
  64. """
  65. for callback in channels[name]:
  66. yield name
  67.  
  68.  
  69. def clear():
  70. global channels
  71. channels = defaultdict(list)
Add Comment
Please, Sign In to add comment