Python nested context manager on multiple lines [duplicate]

Python 3.10 and newer

Starting from Python 3.10, parentheses are allowed, and you can finally do this:

with (
    context1 as a,
    context2 as b
):
    pass

Backslash characters

Two or more physical lines may be joined into logical lines using
backslash characters (\)

(citing the Explicit line joining section)

If you want put context managers on different lines, you can make that work by ending lines with backslashes:

with context1 as a,\
     context2 as b:
    pass

contextlib.ExitStack

contextlib.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.

It’s available in Python 3.3 and newer, and allows to enter a variable number of context managers easily. For just two context managers the usage looks like this:

from contextlib import ExitStack

with ExitStack() as es:
    a = es.enter_context(context1)
    b = es.enter_context(context2)

Nesting

It’s possible to split a context expression across several nested with statements:

With more than one item, the context managers are processed as if
multiple with statements were nested:

with A() as a, B() as b:

suite is equivalent to

with A() as a:
    with B() as b:
        suite

(from The with statement)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)