Skip to content

    Context Managers (with)

    Python · Intermediate

    Definition

    A context manager sets up and tears down a resource automatically using the with statement.

    Guarantees files, locks and connections are closed even on errors.

    Diagram

    with open(...) as fbodyauto close

    Flowchart

    Enter with block (__enter__)Run bodyExit (__exit__) always runs

    Example: Custom context manager

    from contextlib import contextmanager
    @contextmanager
    def tag(n):
        print(f'<{n}>'); yield; print(f'</{n}>')
    with tag('b'):
        print('hi')

    Output: <b> hi </b>

    Key points

    • Always open files with with
    • contextlib simplifies writing them

    Interview questions

    Does __exit__ run on exceptions?

    Yes, and it can choose to suppress the exception.

    More Python topics