Skip to content

Instantly share code, notes, and snippets.

@devilholk
Last active July 3, 2019 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devilholk/1bfc16b581f5f057fd02cd9d1acd32c5 to your computer and use it in GitHub Desktop.
Save devilholk/1bfc16b581f5f057fd02cd9d1acd32c5 to your computer and use it in GitHub Desktop.
Limit recursion with a context handler
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