Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple context `with` statement in Python 2.6

Tags:

python

I like the convenience of the multiple context with statement in Python 2.7:

with open('a.txt') as a, open('b.txt') as b:
   do_many_amazing_things(a, b)

However, I need to maintain compatibility with 2.6.

with was brought to 2.5 via __future__, but I am unable to find anything about the multiple context version being back-ported to 2.6 in the documentation.

Is there something I missed?

EDIT: I am aware that is possible to nest with statements. I am asking if it's possible to use multiple with statements.

like image 707
Austin Richardson Avatar asked Oct 12 '11 19:10

Austin Richardson


1 Answers

If no backward-compatible equivalent of this is possible, I would handle it by making the multiple-context with statement a set of single-context, nested with statements.

with open('a.txt') as a: 
    with open('b.txt') as b:
        do_many_amazing_things(a, b)

EDIT to address your edit:

If you insist on not nesting extra with statements, you can always use contextlib

import contextlib
with contextlib.nested(open("a.txt"), open("b.txt")) as (a, b):
    do_many_amazing_things(a,b)

As for using multiple with statements from the future-imported with, this isn't possible as far as I know

like image 123
jsvk Avatar answered Sep 23 '22 12:09

jsvk