Python Language Context Managers (“with” Statement)


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.


  • with "context_manager"( as "alias")(, "context_manager"( as "alias")?)*:


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:

The translation of the above statement is:

   mgr = (EXPR)
   exit = type(mgr).__exit__  # Not calling it yet
   value = type(mgr).__enter__(mgr)
   exc = True
           VAR = value  # Only if "as VAR" is present
           # The exceptional case is handled here
           exc = False
           if not exit(mgr, *sys.exc_info()):
           # The exception is swallowed if exit() returns true
       # The normal and non-local-goto cases are handled here
       if exc:
           exit(mgr, None, None, None)