17

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.

Austin Richardson
  • 8,078
  • 13
  • 43
  • 49

1 Answers1

20

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

jsvk
  • 1,671
  • 1
  • 14
  • 14
  • Won't the contextlib solution fail if the first file opens but not the second - the first file won't be closed? – Mark Ransom Oct 12 '11 at 19:37
  • @Mark Random I believe so, I should've mentioned that, but it's the closest thing I can find to Austin's intentions – jsvk Oct 12 '11 at 20:11
  • I don't see why you say that the first file won't be closed. If writing it in one way is the same as the other, then the first file will close no matter how the execution flow got out of the first context. – Gabriel Oct 01 '13 at 02:11
  • 2
    @Gabriel this is a bug with contextlib.nested. Info: http://docs.python.org/2/library/contextlib.html#contextlib.nested -> "That means, for example, that using nested() to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file." – jsvk Oct 01 '13 at 02:59