Skip to content

Instantly share code, notes, and snippets.

@Mikael-Lovqvist
Created May 12, 2022 23:24
Show Gist options
  • Save Mikael-Lovqvist/63ab5afa8a2ae431f4d45869838a07ee to your computer and use it in GitHub Desktop.
Save Mikael-Lovqvist/63ab5afa8a2ae431f4d45869838a07ee to your computer and use it in GitHub Desktop.
Defying the rejection of PEP 377
import sys
def dummy_trace(frame, event, *args):
pass
class CancelExecutionException(Exception):
pass
class alternative_execution:
def __init__(self, demo_skip):
self.demo_skip = demo_skip
def __enter__(self):
if self.demo_skip:
f = sys._getframe(1)
#Enable fine grained tracing but tracing function will throw an exception
#First we must initialize the tracing machinery, we do this by installing a dummy function that will just uninstall itself each call (no return value)
#see https://docs.python.org/3/library/sys.html?highlight=fine-grained#sys.settrace for more information about this.
sys.settrace(dummy_trace)
f.f_trace = self.cancel_execution
f.f_trace_opcodes = True
def cancel_execution(self, frame, event, *args):
raise CancelExecutionException()
def __exit__(self, et, ev, tb):
f = sys._getframe(1)
#If the error type is CancelExecutionException we return True to suppress pending exceptions
if et is CancelExecutionException:
return True
#Demonstration
with alternative_execution(False):
print('This statement is always executed') #Prints
with alternative_execution(True):
print('This statement is never executed') #Does not print
print('This is the end')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment