Created
October 15, 2019 23:51
-
-
Save 0xTowel/3dc489688a3c35d4b81651d079613f39 to your computer and use it in GitHub Desktop.
A decorator to limit the number of calls to a function
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
"""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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage: