Skip to content

Instantly share code, notes, and snippets.

@0xTowel
Created October 15, 2019 23:51
Show Gist options
  • Save 0xTowel/3dc489688a3c35d4b81651d079613f39 to your computer and use it in GitHub Desktop.
Save 0xTowel/3dc489688a3c35d4b81651d079613f39 to your computer and use it in GitHub Desktop.
A decorator to limit the number of calls to a function
"""For my friends in OTA.
--Towel, 2019
"""
from functools import wraps
class LimitCalls:
"""A decorator to limit the number of calls to a function.
When the number of executions has exceeded the call limit, calling
the wrapped function will have no effect. If no call limit is specified
the function is limited to one call.
"""
__slots__ = 'executions_left'
DEFAULT_LIMIT = 1
def __init__(self, call_limit=DEFAULT_LIMIT):
self.executions_left = call_limit
def __call__(self, fcn):
@wraps(fcn)
def wrapped(*args, **kwargs):
if self.executions_left > 0:
self.executions_left -= 1
return fcn(*args, **kwargs)
return wrapped
@0xTowel
Copy link
Author

0xTowel commented Oct 16, 2019

Example Usage:

@LimitCalls(2)
def example():
    print('[+] Example Executed.')


example()
example()
example()  # This will have no effect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment