Question:
I am interested in doing a list comprehension inside a Python with
statement, so that I can open multiple context managers at the same time with minimal syntax. I am looking for answers that work with Python 2.7.
Consider the following code example. I want to use the with
statement on variables in an arbitrarily-long list at the same time, preferably in a syntactically-clean fashion.
def do_something(*args):
contexts = {}
with [open(arg) as contexts[str(i)] for i, arg in enumerate(args)]:
do_another_thing(contexts)
do_something("file1.txt", "file2.txt")
Does anybody know if there is a way to involve a list comprehension inside of a with
statement in Python 2.7?
Answers to similar questions:
Here are some things I've already looked at, with an explanation of why they do not suit my purposes:
For Python 2.6-, I could use contextlib.nested
to accomplish this a bit like:
def do_something(*args):
contexts = {}
with nested(*[open(arg) for arg in args]) as [contexts[str(i)] for i in range(len(args))]:
do_another_thing(contexts)
However, this is deprecated in Python 2.7+, so I am assuming it is bad practice to use.
Instead, the new syntax was given on this SO answer, as well as this SO answer:
with A() as a, B() as b, C() as c:
doSomething(a,b,c)
However, I need to be able to deal with an arbitrary input list, as in the example I gave above. This is why I favour list comprehension.
For Python 3.3+, this SO answer described how this could be accomplished by using ExitStack
. However, I am working in Python 2.7.
There is also this solution, but I would prefer to not write my own class to accomplish this.
Is there any hope of combining a list comprehension and a with
statement in Python 2.7?
Update 1-3: Updated example to better emphasize the functionality I am looking for
Update 4: Found another similar question. This one has an answer which also suggests ExitStack
, a function that is not available in 2.7.