Last active
September 7, 2017 19:40
-
-
Save flying-sheep/86dfcc1bdd71a33fa3483b83e254084c to your computer and use it in GitHub Desktop.
A context manager that can skip its body.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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