Aug. 13, 2013
7:15 p.m.
13.08.13 18:04, Masklinn написав(ла):
Please note that enter_context will return the result of object.__enter__, so:
with contextlib.ExitStack() as cm: file = cm.enter_context(open(path1)) if condition1 else None file2 = cm.enter_context(open(path2)) if condition2 else None process(file, file2, ...)
Well, it works. However there are two disadvantages: 1. You need import contextlib. 2. cm.enter_context() increases a length of already long lines so you need split lines. N.B. Currently ExitStack used only in two places in stdlib (and I am the originator of both changes). In most cases it is simpler to do without ExitStack.