with文はカンマ区切りで複数のコンテキストマネージャを渡せる
これ知りませんでした。
Python2.7からはwith文にカンマ区切りで複数のコンテキストマネージャを渡すことが出来て、with文のネストを1行で書けるらしいです。
http://www.python.jp/doc/release/reference/compound_stmts.html#with
ここにある通り、
with A() as a: with B() as b: suite
これは、
with A() as a, B() as b: suite
こう書けます。
組み込みのopen関数でファイルを開くときにwithと共に使うと必ずcloseしてくれるので、一度に二つファイルを開いて処理するプログラムを書くときとかに便利ですね。
file1 = open("foo.txt", "r") file2 = open("bar.txt", "r") with file1, file2: for x in file1: do_something(x) for y in file2: do_another_one(y)