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?
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 .
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With