Conditional with statement in Python

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

    I have found that the @Anentropic answer is incomplete.

    from conditional import conditional
    
    a = 1 # can be None
    
    if not a is None:
      b = 1
    
    class WithNone:
      def __enter__(self):
        return self
      def __exit__(self, type, value, tb):
        pass
    
    def foo(x):
      print(x)
      return WithNone()
    
    with conditional(not a is None, foo(b) if not a is None else None):
      print(123)
    

    The complete conditional usage required 3 conditions instead of 1 because of:

    1. NameError: name 'b' is not defined in case if not defined a
    2. the function foo still must return enterable object, otherwise: AttributeError: 'NoneType' object has no attribute '__enter__'

提交回复
热议问题