from __future__ import print_function import sys import inspect import traceback class Context(object): exception = type('with', (Exception,), {}) def __enter__(self): # setup the anonymous code-block capture def __raise(*args): raise self.exception frame = inspect.currentframe().f_back frame.f_trace = __raise sys.settrace(True) # this triggers the frame.f_trace hook return self def __exit__(self, exception, *args): if not exception in (None, self.exception): return False return True try: \ with Context() as zero: print ('zero', zero) print ('ZERO', zero) except: traceback.print_exc() try: with \ Context() as one : print ('one', one) print ('ONE', one) except: traceback.print_exc() try: with Context() \ as two : print ('two', two) print ('TWO', two) except: traceback.print_exc() try: with Context() as \ three : print ('three', three) print ('THREE', three) except: traceback.print_exc() try: with Context() as four \ : print ('four', four) print ('FOUR', four) except: traceback.print_exc() try: with Context() as five : \ print ('five', five) print ('FIVE', five) except: traceback.print_exc()