This question was asked before Python 3.4 existed but with 3.4 you can use contextlib.supress
,
suppressing your own personal exception.
See that this (runnable as is) code
from contextlib import suppress
class InterruptWithBlock(UserWarning):
"""To be used to interrupt the march of a with"""
condition = True
with suppress(InterruptWithBlock):
print('before condition')
if condition: raise InterruptWithBlock()
print('after condition')
# Will not print 'after condition` if condition is True.
So with the code in the question, you'd do:
with suppress(InterruptWithBlock) as _, open(path) as f:
print('before condition')
if <condition>: raise InterruptWithBlock()
print('after condition')
Note: If you're (still) before 3.4, you can still make your own suppress
context manager easily.
if not <condition>
is undesirable in your situation. – Glover