Can I have a context manager that sometimes fails, in which case the code inside the with statement just doesn't execute?
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 try-catch, but this is not preferred. I could also do the following, but it is also ugly.
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.'
source
share