Conditional with statement in Python

前端 未结 8 1297
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  • 2020-11-28 06:28

    As of Python 3.7 you can use contextlib.nullcontext:

    from contextlib import nullcontext
    
    if needs_with():
        cm = get_stuff()
    else:
        cm = nullcontext()
    
    with cm as gs:
        # Do stuff
    

    contextlib.nullcontext is pretty much just a no-op context manager. You can pass it an argument that it will yield, if you depend on something existing after the as:

    >>> with nullcontext(5) as value:
    ...     print(value)
    ...
    5
    

    Otherwise it'll just return None:

    >>> with nullcontext() as value:
    ...     print(value)
    ...
    None
    

    It's super neat, check out the docs for it here: https://docs.python.org/3/library/contextlib.html#contextlib.nullcontext

    0 讨论(0)
  • 2020-11-28 06:28

    A third-party option to achieve exactly this:
    https://pypi.python.org/pypi/conditional

    from conditional import conditional
    
    with conditional(needs_with(), get_stuff()):
        # do stuff
    
    0 讨论(0)
提交回复
热议问题