Last active
July 3, 2019 22:33
-
-
Save devilholk/1bfc16b581f5f057fd02cd9d1acd32c5 to your computer and use it in GitHub Desktop.
Limit recursion with a context handler
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, collections | |
class max_stack_level: | |
active = collections.Counter() | |
def __init__(self, max): | |
self.max = max | |
def __enter__(self): | |
frame = sys._getframe(1) | |
self.tag = frame.f_code, frame.f_lineno | |
self.active[self.tag] += 1 | |
if self.active[self.tag] >= self.max: | |
raise RecursionError(f'Recursion limited by {self}') | |
return self | |
def __exit__(self, e, et, tb): | |
self.active[self.tag] -= 1 | |
def my_thing(): | |
print('MyThing!') | |
with max_stack_level(3): | |
my_thing() | |
my_thing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment