[Python-ideas] with None (Was: Re: Enhanced context managers with ContextManagerExit and None)
Serhiy Storchaka
storchaka at gmail.com
Tue Aug 13 21:15:30 CEST 2013
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.
More information about the Python-ideas
mailing list