event.py 652 B

12345678910111213141516171819202122232425
  1. '''Event bus implementation'''
  2. # https://stackoverflow.com/questions/1092531/event-system-in-python
  3. class Bus(object):
  4. def __init__(self):
  5. self.__handlers = []
  6. def __iadd__(self, handler):
  7. self.__handlers.append(handler)
  8. return self
  9. def __isub__(self, handler):
  10. self.__handlers.remove(handler)
  11. return self
  12. def fire(self, *args, **kwargs):
  13. for handler in self.__handlers:
  14. handler(*args, **kwargs)
  15. def clear_handlers(self, obj=None):
  16. for handler in self.__handlers:
  17. if not obj or handler.__self__ == obj:
  18. self -= handler
  19. bus = Bus()