Skip to content

Instantly share code, notes, and snippets.

@tvogels
Created September 13, 2021 16:24
Show Gist options
  • Save tvogels/c73d2318f90ad6da2569e715a02b6bf8 to your computer and use it in GitHub Desktop.
Save tvogels/c73d2318f90ad6da2569e715a02b6bf8 to your computer and use it in GitHub Desktop.
with probability block
import random
import sys
class probability:
"""Based on https://stackoverflow.com/questions/12594148/skipping-execution-of-with-block"""
def __init__(self, probability):
assert probability >= 0 and probability <= 1
self.probability = probability
def __enter__(self):
if random.random() > self.probability:
sys.settrace(lambda *args, **keys: None)
frame = sys._getframe(1)
frame.f_trace = self.trace
def trace(self, frame, event, arg):
raise SkipWithBlock()
def __exit__(self, type, value, traceback):
if type is None:
return # No exception
if issubclass(type, SkipWithBlock):
return True # Suppress special SkipWithBlock exception
class SkipWithBlock(Exception):
pass
# Example
if __name__ == "__main__":
for i in range(10):
with probability(0.5):
print(f"{i}. hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment