Dynamically Pass Parameters To Function
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, af
Solution 1:
Write a decorator, and use a splat operator to handle arbitrary arguments.
Example:
def pause_wrapper(x, n):
def decorator(f):
config = [x, time.time()+n]
def wrapped(*args, **kwargs):
ifconfig[0] == 0:
time.sleep(config[1] - time.time())
config = [x, time.time() + n]
return f(*args, **kwargs)
return wrapped
return decorator
and usage:
@pause_wrapper(x, n)deffunction(a, b, c):
...
The *args
and **kwargs
are informally called "splat" arguments. A function that takes *args, **kwargs
receives all positional parameters in the tuple args
and all keyword arguments in the dictionary kwargs
. (You can have other arguments besides the splats, in which case the splats soak up all arguments not sent to named arguments).
Passing *args
and **kwargs
has the opposite effect, passing the contents of args
as extra positional parameters, and kwargs
as keyword parameters.
Using both allows you to handle any set of arguments, in or out, letting you do transparent wrapping (like this example).
Solution 2:
this is basically what decorators were made for
from collections import defaultdict
classcounted:
calls = defaultdict(int)
def__init__(self,x,n):
self.x = x
self.n = n
def__call__(self,fn,*args,**kwargs):
results = fn(*args,**kwargs)
calls[fn.__name__] += 1#do something with the count ... @counted(3,9)deffunctionWhatever(arg1,arg2,arg3,**kwargs):
return"55"
functionWhatever(1,2,3,something=5)
Post a Comment for "Dynamically Pass Parameters To Function"