This rule raises an issue when a with statement is nested inside another with and both can be written as a single with with multiple context managers.

Why is this an issue?

A single with statement can open several context managers at once:

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

Nesting a second with only to acquire another context manager adds an indentation level without changing semantics. The combined form is the idiomatic style: it keeps related resource setup on one line and makes the shared body easier to read.

What is the potential impact?

Exceptions

Nested with statements are acceptable when the inner with is not the only statement in the outer body.

They are also acceptable when a comment between the nested with statements explains why they were not combined, for example because Python 3.0 has no multi-item with.

How to fix it

Rewrite the nested with statements as one with that lists every context manager, separated by commas.

On Python 3.0, multi-item with is not available. Leave the statements nested and add a comment between them explaining why they were not merged.

Code examples

Noncompliant code example

with open("a.txt") as a:
    with open("b.txt") as b:  # Noncompliant
        process(a, b)

Compliant solution

with open("a.txt") as a, open("b.txt") as b:
    process(a, b)

Compliant solution

with open("a.txt") as a:
    # Add a comment explaining why these with statements are not merged. For example:
    # These contexts can't be merged as Python 3.0 has no multi-item with
    with open("b.txt") as b:
        process(a, b)

Resources

Documentation

External coding guidelines