Created
September 13, 2021 16:24
-
-
Save tvogels/c73d2318f90ad6da2569e715a02b6bf8 to your computer and use it in GitHub Desktop.
with probability block
This file contains hidden or 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 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