Conditional with statement in Python

前端 未结 8 1326
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  Happy的楠姐
    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

提交回复
热议问题