これはどう?
class ListContext:
def __init__(self, l):
self.l = l
def __enter__(self):
for x in self.l:
x.__enter__()
return self.l
def __exit__(self, type, value, traceback):
for x in self.l:
x.__exit__(type, value, traceback)
arr = ['a', 'b', 'c']
with ListContext([open(fn, 'w') for fn in arr]) as files:
print files
print files
出力は次のとおりです。
[<open file 'a', mode 'w' at 0x7f43d655e390>, <open file 'b', mode 'w' at 0x7f43d655e420>, <open file 'c', mode 'w' at 0x7f43d655e4b0>]
[<closed file 'a', mode 'w' at 0x7f43d655e390>, <closed file 'b', mode 'w' at 0x7f43d655e420>, <closed file 'c', mode 'w' at 0x7f43d655e4b0>]
with コンテキスト内で開いていて、外側で閉じていることに注意してください。
これは Pythonコンテキスト マネージャー APIを使用しています。
編集:これは既に存在するようですが、非推奨です: contextlibとthis SO questionを参照してください。次のように使用します。
import contextlib
with contextlib.nested(*[open(fn, 'w') for fn in arr]) as files:
print files
print files