fork download
  1. # An attempt to emulate scope guard statements of the D Programming Language
  2. # see: http://d...content-available-to-author-only...s.com/2.0/statement.html#ScopeGuardStatement
  3.  
  4. def noop(*args, **kwargs):
  5. pass
  6.  
  7. def mkCbAdder(typ):
  8. def adder(self, cb):
  9. self.callbacks.append( (typ, cb) )
  10. return adder
  11.  
  12. class Scope(object):
  13.  
  14. def __init__(self):
  15. self.callbacks = []
  16.  
  17. exit = property(noop, mkCbAdder('exit'))
  18. success = property(noop, mkCbAdder('ok'))
  19. failure = property(noop, mkCbAdder('fail'))
  20.  
  21. def __enter__(self):
  22. return self
  23.  
  24. def __exit__(self, type, value, traceback):
  25. ok = value is None
  26. while self.callbacks:
  27. typ, cb = self.callbacks.pop()
  28. if typ is 'exit':
  29. cb()
  30. elif ok and typ is 'ok':
  31. cb()
  32. elif not ok and (typ is 'fail'):
  33. cb()
  34.  
  35.  
  36. def write(arg):
  37. return lambda: print(arg, end="")
  38.  
  39.  
  40. write(1)()
  41. with Scope() as s:
  42. write(2)()
  43. s.exit = write(3)
  44. s.exit = write(4)
  45. write(5)()
  46.  
  47. # 12543
  48.  
  49. print()
  50.  
  51. with Scope() as s:
  52. s.exit = write(1)
  53. s.success = write(2)
  54. s.exit = write(3)
  55. s.success = write(4)
  56.  
  57. # 4321
  58.  
  59. print()
  60.  
  61. try:
  62. with Scope() as s:
  63. s.exit = write(1)
  64. s.success = write(2)
  65. s.failure = write(3)
  66. raise Exception("msg")
  67. s.exit = write(4)
  68. s.success = write(5)
  69. s.failure = write(6)
  70.  
  71. except Exception as e:
  72. pass
  73.  
  74. # 31
  75.  
Success #stdin #stdout 0.02s 5908KB
stdin
Standard input is empty
stdout
12543
4321
31