Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active September 7, 2017 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flying-sheep/86dfcc1bdd71a33fa3483b83e254084c to your computer and use it in GitHub Desktop.
Save flying-sheep/86dfcc1bdd71a33fa3483b83e254084c to your computer and use it in GitHub Desktop.
A context manager that can skip its body.
import sys
import inspect
class _UnpackMarker(Exception): pass
class unpack:
def __init__(self, pred):
self.pred = pred
def __enter__(self):
if self.pred:
return self.pred
# else skip the with block’s body
sys.settrace(lambda *args, **kw: None)
frame = inspect.currentframe().f_back
frame.f_trace = self.trace
def trace(self, frame, event, arg):
raise _UnpackMarker
def __exit__(self, type, value, traceback):
if type is _UnpackMarker:
return True # suppress the exception
if __name__ == '__main__':
with unpack(True) as result:
assert result is True
print('This should print')
with unpack(False) as result:
print('This should not print')
try:
with unpack(True) as result:
raise RuntimeError('This should raise')
except RuntimeError as e:
print(str(e))
else:
print('This should not display')
try:
raise RuntimeError('This should also raise')
except RuntimeError as e:
print(str(e))
else:
print('This should also not display')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment