import sys import contextlib import traceback class AnException(Exception): pass @contextlib.contextmanager def causes_exception(): "raise AnException" pass try: raise AnException("yikes") yield 1 finally: pass @contextlib.contextmanager def what_exception(): "suffocate AnException" pass try: yield None except AnException: # what exception? things are just fine. pass finally: pass @contextlib.contextmanager def cleanup_or_finish(): try: print "setup, good" yield None except Exception, e: print "cleanup, bad" traceback.print_exception(*sys.exc_info()) else: print "finished, no exception seen. good." print print "using nested with statements:" print with cleanup_or_finish(): with what_exception(): with causes_exception(): print "inner, should never print" print print "using nested():" print with contextlib.nested(cleanup_or_finish(), what_exception(), causes_exception()): print "iieee, should never get here"