Are multiple `with` statements on the same line equivalent to nested` with` statements in python?

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 as awell as bchange the global variables (here the tensor flow) and bdepend on the changes made a. So, I know that the 2nd form is safe to use, but equivalent to reducing it to the 1st form?

+4
source share
3 answers

Yes, listing several statements withon the same line exactly matches nesting them according to the Python 2.7 reference :

, :

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

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

Python 3.

+7

. .

0

As others have said, this is the same result. Here is a more detailed example of how this syntax can be used:

blah.txt

1
2
3
4
5

I can open one file and write its contents to another file in a short way:

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
0
source

Source: https://habr.com/ru/post/1673659/


All Articles