context manager
with context_manager:
context_manager.__enter__()
body
context_manager.__exit__()
context manager protocol
\_\_enter\_\_(self):
\_\_exit\_\_(self,
exc_type,
exc_val,
exc_tb
)__enter__() return …
context manager
default behaviour with exceptions in with block
__exit__() propagates exeptions
to propagates exceptions from with block …
__exit__() must return False
standart library for working with context managers
contextlib
context manager decorator
@contextlib.contextmanager
def my_context_manager():
#
try:
yield [value]
#
except:raise
with my_context_manager() as x:
multiple context managers
with cm1() as a, cm2() as b, … :