fork download
  1. """An example of the mark and recapture decorator pattern,
  2. designed to make connecting bound methods as callbacks easy.
  3. Gareth Latty <gareth@lattyware.co.uk>
  4. http://b...content-available-to-author-only...o.uk/post/29793030567/mark-and-recapture-decorators-in-python"""
  5.  
  6. import inspect
  7.  
  8. def connect(signal, f):
  9. print(signal, f)
  10.  
  11. def naive_callback(*args):
  12. def decorate(f):
  13. connect(args, f)
  14. return f
  15. return decorate
  16.  
  17. def callback(*args):
  18. def decorate(f):
  19. try:
  20. f._marks.add(args)
  21. except AttributeError:
  22. f._marks = {args}
  23. return f
  24. return decorate
  25.  
  26. def connect_callbacks(obj):
  27. for _, f in inspect.getmembers(obj, inspect.ismethod):
  28. try:
  29. for mark in f.__func__._marks:
  30. connect(mark, f)
  31. except AttributeError:
  32. pass
  33.  
  34. class Test:
  35. def __init__(self):
  36. connect_callbacks(self)
  37.  
  38. @naive_callback("test")
  39. def test1():
  40. pass
  41.  
  42. @callback("test")
  43. def test2():
  44. pass
  45.  
  46. test = Test()
Success #stdin #stdout 0.06s 6324KB
stdin
Standard input is empty
stdout
('test',) <function test1 at 0xb72bf06c>
('test',) <bound method Test.test2 of <__main__.Test object at 0xb72bb9ec>>