Join nested with statements

Python pattern

Join nested with statements into a single one. Rule SIM117 from flake8-simplify.

Limitations:

  • Only two nested with statements are joined.

Join with statements

BEFORE
with open("file1.txt") as f1:
    with open("file2.txt", "r+") as f2:
        pass

with A() as a, B() as b:
    with C() as c:
        pass

with A() as a:
    with B() as b, C() as c:
        pass

# TODO: should be joined into a single with
with A() as a:
    with B() as b:
        with C() as c:
            pass
AFTER
with open("file1.txt") as f1, open("file2.txt", "r+") as f2:
    pass

with A() as a, B() as b, C() as c:
    pass

with A() as a, B() as b, C() as c:
    pass

# TODO: should be joined into a single with
with A() as a, B() as b:
    with C() as c:
        pass