Are multiple `with` statements on one line equivalent to nested `with` statements, in python?

Yes, listing multiple with statements on one line is exactly the same as nesting them, according to the Python 2.7 language reference:

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

Similar language appears in the Python 3 language reference.

Update for 3.10+

Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines.

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

Leave a Comment

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