[Python-ideas] with None (Was: Re: Enhanced context managers with ContextManagerExit and None)

Masklinn masklinn at masklinn.net
Tue Aug 13 17:04:24 CEST 2013


On 2013-08-13, at 16:48 , Serhiy Storchaka wrote:
> 
> 3. With ExitStack:
> 
>    import contextlib
>    with contextlib.ExitStack() as cm:
>        if ...:
>            file = open(...)
>            cm.enter_context(file)
>        else:
>            file = None
>        if ...:
>            file2 = open(...)
>            cm.enter_context(file2)
>        else:
>            file2 = None
>        process(file, file2, …)

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, ...)

or if you really like conditional statements:

with contextlib.ExitStack() as cm
    file = None
    file2 = None
    if condition1:
        file = cm.enter_context(open(path1))
    if condition2:
        file2 = cm.enter_context(open(path2))
    process(file, file2, ...)


More information about the Python-ideas mailing list