Conditional with statement in Python

前端 未结 8 1316
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 06:04

Is there a way to begin a block of code with a with statement, but conditionally?

Something like:

if needs_with():
    with get_stuff() as gs:

# do          


        
8条回答
  •  -上瘾入骨i
    2020-11-28 06:26

    It was hard to find @farsil's nifty Python 3.3 one-liner, so here it is in its own answer:

    with ExitStack() if not needs_with() else get_stuff() as gs:
         # do stuff
    

    Note that ExitStack should come first, otherwise get_stuff() will be evaluated.

提交回复
热议问题