Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple variables in a 'with' statement?

Is it possible to declare more than one variable using a with statement in Python?

Something like:

from __future__ import with_statement  with open("out.txt","wt"), open("in.txt") as file_out, file_in:     for line in file_in:         file_out.write(line) 

... or is cleaning up two resources at the same time the problem?

like image 407
pufferfish Avatar asked May 21 '09 14:05

pufferfish


People also ask

How do you do multiple variables in an if statement?

First, use a SWITCH(TRUE()...) statement instead of nested IF statements. Far cleaner, more readable and easier to modify. Second, use the logical operators && (AND) and || (OR) to combine multiple criteria.

Can I have multiple variables in a for loop?

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can I use multiple with in Python?

Because Python's original parser is LL(1), it cannot distinguish between "multiple context managers" with (A(), B()): and "tuple of values" with (A(), B())[0]: . The new parser can properly parse multiple context managers surrounded by parentheses.

Can you use += with multiple variables?

No, you cannot. You cannot use augmented assignment together with multiple targets.


1 Answers

It is possible in Python 3 since v3.1 and Python 2.7. The new with syntax supports multiple context managers:

with A() as a, B() as b, C() as c:     doSomething(a,b,c) 

Unlike the contextlib.nested, this guarantees that a and b will have their __exit__()'s called even if C() or it's __enter__() method raises an exception.

You can also use earlier variables in later definitions (h/t Ahmad below):

with A() as a, B(a) as b, C(a, b) as c:     doSomething(a, c) 

As of Python 3.10, you can use parentheses:

with (     A() as a,      B(a) as b,      C(a, b) as c, ):     doSomething(a, c) 
like image 144
Rafał Dowgird Avatar answered Oct 01 '22 09:10

Rafał Dowgird