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
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:
NameError: name 'b' is not defined in case if not defined afoo still must return enterable object, otherwise: AttributeError: 'NoneType' object has no attribute '__enter__'