Conditional with statement in Python

前端 未结 8 1335
佛祖请我去吃肉
佛祖请我去吃肉 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

    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
    

提交回复
热议问题