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?
Since Python 3.3, you can use the class
ExitStack
from thecontextlib
module.It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
The canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
Here is a generic example:
Output:
I think you want to do this instead:
It is possible in Python 3 since v3.1 and Python 2.7. The new
with
syntax supports multiple context managers:Unlike the
contextlib.nested
, this guarantees thata
andb
will have their__exit__()
's called even ifC()
or it's__enter__()
method raises an exception.Note that if you split the variables into lines, you must use backslashes to wrap the newlines.
Parentheses don't work, since Python creates a tuple instead.
Since tuples lack a
__enter__
attribute, you get an error (undescriptive and does not identify class type):contextlib.nested
supports this:Update:
To quote the documentation, regarding
contextlib.nested
:See Rafał Dowgird's answer for more information.