Can I have a context manager which occasionally does not yield, and in which case the code within the with statement are simply not executed?
import contextlib
@contextlib.contextmanager
def MayNotYield(to_yield):
if to_yield:
yield
with MayNotYield(True):
print 'This works.'
with MayNotYield(False):
print 'This errors.'
I could ask the user to wrap the with statement with a try-catch, but that is not preferred. I could also do the following but it is ugly too.
import contextlib
@contextlib.contextmanager
def AlwaysYields(to_yield):
if to_yield:
yield 1
else:
yield 2
with AlwaysYields(True) as result:
if result == 1:
print 'This works.'
yield. It looks like you're trying to combine anifstatement with a context manager to get around the inability to assign in anifstatement, not trying to manage resources.