Last active
September 5, 2020 17:40
-
-
Save traverseda/4bdc8d6446b6cc15d4ef66df229a5d6c to your computer and use it in GitHub Desktop.
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
""" | |
Horrible hacks to allow context managers to exit early, *not* running | |
whatever code they're wrapping. I'm not sure if this is a reasonable | |
thing to do or not.... | |
""" | |
import sys | |
class ExitEarlyException(Exception): | |
"""This is an exception that python | |
will always ignore. It's part of a hack | |
that allows context manager (`with` statements) | |
to exit without ever running the code they're | |
wrapping. | |
""" | |
pass | |
oldhook = sys.excepthook | |
def manage_exit_early_hook(exctype, value, traceback): | |
"""Part of a hack that lets context managers (`with` statements) | |
exit without ever running the code that they're wrapping | |
""" | |
if exctype == ExitEarlyException: pass | |
else: oldhook(exctype, value, traceback) | |
sys.excepthook = manage_exit_early_hook | |
from contextlib import contextmanager | |
@contextmanager | |
def exit_early(dont_run): | |
if dont_run: | |
raise ExitEarlyException | |
yield | |
with exit_early(False): | |
print("This runs") | |
with exit_early(True): | |
print("This doesn't run") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment