Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple `with` statements on one 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 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?

like image 594
David Parks Avatar asked Mar 31 '17 01:03

David Parks


People also ask

How do you do multiple If statements in one line Python?

To put an if-then-else statement in one line, use Python's ternary operator x if c else y . This returns the result of expression x if the Boolean condition c evaluates to True . Otherwise, the ternary operator returns the alternative expression y .

Can I have two with statements in Python?

The documentation says: Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they're used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

Which of the following are true regarding multiple statements per line in Python?

Multiple statements on the same line are separated by the & character. Specifying more than one statement on a line is typically not considered Pythonic, but may be acceptable if it enhances readability. Only variable assignment statements may occur multiply on a single line. ​

What is the with statement in Python?

In Python, the with statement replaces a try-catch block with a concise shorthand. More importantly, it ensures closing resources right after processing them. A common example of using the with statement is reading or writing to a file. A function or class that supports the with statement is known as a context manager.


Video Answer


2 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

Exactly the same language appears in the Python 3 language reference.

like image 60
Kevin Avatar answered Sep 21 '22 05:09

Kevin


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
like image 31
blacksite Avatar answered Sep 23 '22 05:09

blacksite