import contextlib @contextlib.contextmanager def make_context(): print ' entering' try: yield {} except RuntimeError, err: print ' ERROR:', err finally: print ' exiting'
И наоборот, если не писать:
import contextlib @contextlib.contextmanager def make_context(name): print 'entering:', name yield name print 'exiting :', name with make_context('something'): print 'middle' raise Exception('something')