While Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes. This topic explains and demonstrates the use of Python's context managers.
Context managers are defined in PEP 343. They are intended to be used as more succinct mechanism for resource management than try ... finally
constructs. The formal definition is as follows.
In this PEP, context managers provide
__enter__()
and__exit__()
methods that are invoked on entry to and exit from the body of the with statement.
It then goes on to define the with
statement as follows.
with EXPR as VAR: BLOCK
The translation of the above statement is:
mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present BLOCK except: # The exceptional case is handled here exc = False if not exit(mgr, *sys.exc_info()): raise # The exception is swallowed if exit() returns true finally: # The normal and non-local-goto cases are handled here if exc: exit(mgr, None, None, None)