Multiple with statements in Python 2.7 using a list comprehension -


question:

i interested in doing list comprehension inside python with statement, can open multiple context managers @ same time minimal syntax. looking answers work python 2.7.

consider following code example. want use with statement on variables in arbitrarily-long list at same time, preferably in syntactically-clean fashion.

def do_something(*args):     contexts = {}     [open(arg) contexts[str(i)] i, arg in enumerate(args)]:         do_another_thing(contexts)  do_something("file1.txt", "file2.txt") 

does know if there way involve list comprehension inside of with statement in python 2.7?


answers similar questions:

here things i've looked at, explanation of why not suit purposes:

for python 2.6-, use contextlib.nested accomplish bit like:

def do_something(*args):     contexts = {}     nested(*[open(arg) arg in args]) [contexts[str(i)] in range(len(args))]:         do_another_thing(contexts) 

however, deprecated in python 2.7+, assuming bad practice use.

instead, new syntax given on this answer, this answer:

with a() a, b() b, c() c:     dosomething(a,b,c) 

however, need able deal arbitrary input list, in example gave above. why favour list comprehension.

for python 3.3+, this answer described how accomplished using exitstack. however, working in python 2.7.

there this solution, prefer not write own class accomplish this.

is there hope of combining list comprehension , with statement in python 2.7?

update 1-3: updated example better emphasize functionality looking for

update 4: found similar question. 1 has answer suggests exitstack, function not available in 2.7.

doing tricky, handling exceptions occur while opening or closing files. i'd recommend getting library contextlib2 implements contextlib.exitstack functionality. can do

with contextlib2.exitstack() stack:     files = [stack.enter_context(open(arg)) arg in args]     ... 

just using contextlib.exitstack python 3, , handled correctly you.


Comments