Are multiple `with` statements on one line equivalent to nested `with` statements, in python?
Question:
Are these two statements equivalent?
with A() as a, B() as b:
# do something
with A() as a:
with B() as b:
# do something
I ask because both a
and b
alter global variables (tensorflow here) and b
depends on changes made by a
. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?
Answers:
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
Absolutely identical. Just depends on your personal preference.
As others have said, it’s the same result. Here’s a more detailed example of how this syntax might be used:
blah.txt
1
2
3
4
5
I can open one file and write its contents to another file in a succinct manner:
with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
for line in infile:
outfile.write(str(line))
foo.txt now contains:
1
2
3
4
5
Are these two statements equivalent?
with A() as a, B() as b:
# do something
with A() as a:
with B() as b:
# do something
I ask because both a
and b
alter global variables (tensorflow here) and b
depends on changes made by a
. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?
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
Absolutely identical. Just depends on your personal preference.
As others have said, it’s the same result. Here’s a more detailed example of how this syntax might be used:
blah.txt
1
2
3
4
5
I can open one file and write its contents to another file in a succinct manner:
with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
for line in infile:
outfile.write(str(line))
foo.txt now contains:
1
2
3
4
5