Programming Search⌘K

Featurecore

Context managers

Also called __enter__, __exit__, contextlib.contextmanager, contextlib.suppress, ExitStack, context manager protocol.

A context manager has __enter__ and __exit__ methods, which the with statement calls around its block. contextlib makes them from generators and has ready ones such as suppress and ExitStack.

Language
Python

Synopsis

class Timer:
    def __enter__(self):
        print('enter')
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        print('exit', exc_type.__name__ if exc_type else None)
        return False

with Timer() as t:
    print('body', type(t).__name__)

try:
    with Timer():
        raise KeyError('k')
except KeyError:
    print('KeyError went on')
Output
enter
body Timer
exit None
enter
exit KeyError
KeyError went on

The with statement calls __enter__ before the block and __exit__ after it. __exit__ gets the exception, and because it returns False the exception goes on.

Semantics

r1. "A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code."1 "Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc."1

r2. __enter__: "The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any."1

r3. __exit__(self, exc_type, exc_value, traceback): "The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None."1 "If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value."1 "Note that exit() methods should not reraise the passed-in exception; this is the caller’s responsibility."1

r4. contextlib.contextmanager "is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate enter() and exit() methods."3 The generator "must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any."3 "If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred."3 Example: generator.

r5. suppress returns "a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement."3 Example: suppress.

r6. ExitStack is "A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data."3 "Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed".3 Example: exitstack.

Examples

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f'<{name}>')
    try:
        yield name
    finally:
        print(f'</{name}>')

with tag('p') as t:
    print('text in', t)

try:
    with tag('b'):
        raise ValueError('bad')
except ValueError as err:
    print('error:', err)
Output
<p>
text in p
</p>
<b>
</b>
error: bad

The code before yield runs on entry and the code after it runs on exit. The try statement around yield closes the tag when the block raises (rule r4).

import os
from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('no-such-file.tmp')
print('went on')
Output
went on

This is the same as a try statement with except FileNotFoundError: pass (rule r5).

from contextlib import ExitStack

class Resource:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print('open', self.name)
        return self
    def __exit__(self, *exc):
        print('close', self.name)

with ExitStack() as stack:
    items = [stack.enter_context(Resource(n)) for n in ['a', 'b', 'c']]
    stack.callback(print, 'callback')
    print('using', len(items))
Output
open a
open b
open c
using 3
callback
close c
close b
close a

The number of resources comes from the data. ExitStack closes them in reverse order (rule r6).

Pitfalls

A true return value from __exit__ hides every exception:

This code runs but gives a wrong answer on purpose.

class Quiet:
    def __enter__(self):
        return self
    def __exit__(self, *exc):
        print('cleaning up')
        return True

def average(values):
    with Quiet():
        return sum(values) / len(values)

print(average([]))
Output
cleaning up
None

The ZeroDivisionError is suppressed, and the function returns None (rule r3). Return False or None, unless suppression is the purpose.

A generator without try and finally does not clean up after an error:

This code runs but gives a wrong answer on purpose.

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f'<{name}>')
    yield
    print(f'</{name}>')

try:
    with tag('b'):
        raise ValueError('bad')
except ValueError:
    print('error')
Output
<b>
error

The exception is raised again at the yield (rule r4), so the line after it does not run and the tag stays open. Put the yield in a try statement with a finally clause.

Comparison

Go has no protocol like __enter__ and __exit__. A Go function calls defer with the clean-up call, and "Deferred functions are executed in LIFO order".4 ExitStack gives the same last-in, first-out order in Python (rule r6).

References

  1. The Python Language Reference, 3. Data model, 3.3.9. With Statement Context Managers
  2. The Python Language Reference, 8. Compound statements, 8.5. The with statement
  3. contextlib, Utilities for with-statement contexts, contextmanager; suppress; ExitStack
  4. Effective Go, Defer

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source