I need to keep track of the number of times each function in a collection has been called. If a function is called more than x
times within n
seconds, my program needs to pause, after which the count for that function is reset.
My functions calls might look something like this:
a(1)
b(1,param2=2, param3=3)
c(1,param3=3)
My best idea is to have a wrapper function keep track of all of the limits. Something like
def wrapper(function, function_params,x,n):
if not hasattr(wrapper, "function_dict"):
wrapper.function_dict = {}
if function not in wrapper.function_dict.keys():
wrapper.function_dict[function] = {
remaining = x, expires = time.time() + n
}
remaining = wrapper.function_dict[function]['remaining']
expires = wrapper.function_dict[function]['expires']
if remaining == 0:
time.sleep(expires - time.time())
wrapper.function_dict[function] = {
remaining = x, expires = time.time() + n
}
results = ????? # call function, this is what I don't know how to do
wrapper.function_dict[function]['remaining'] -= 1
My question is, how to I handle the parameters for the functions? I'm not sure how exactly to account for the fact that there might be a variable number of parameters, and that some might be named. For example, the function definition for c
might be:
def c(param1,param2=2, param3=3):
return param1 + param2 + param3
But I might need to call it with only param1
and param3
.
Do I have the right general approach? This feels like something I could accomplish with the **
operator, but I'm stuck on how exactly to proceed.