Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python function multiple times with different arguments

Tags:

python

Hi I need to have a function that would take a function and return a function that will run that argument function eg. 1000 times and each time evaluate it's argument. I have something like this:

def runner(f):
    def inner(*args):
        for i in xrange(1000):
            f(*args)
    return inner

But it seems that invocation like this:runner(f)(random.randint(1,UPPER_BOUND)) runs f 1000 times with the same argument. How to do it correctly?

like image 721
k_wisniewski Avatar asked Jan 18 '23 19:01

k_wisniewski


1 Answers

The problem you're encountering is that random.randint(1,UPPER_BOUND) is being evaluated once at the time the inner() function returned by runner() is called. What you need is to delay the evaluation until later.

You could try something like this:

>>> def runner(f, callable):
...   def inner():
...     for i in xrange(1000):
...       f(*callable())
...   return inner
... 
>>> runner(f, lambda: (random.randint(1, 1000),))()
603
385
321
etc.

Note that callable is called each time the original function f is called. Also note that callable must return a sequence type, like a tuple or list.

Edit: if you need to pass other arguments to f you can do it with something like this:

>>> def runner(f, callable):
...   def inner(*args, **kwds):
...     for i in xrange(1000):
...       pos = list(callable())
...       pos.extend(args)
...       f(*pos, **kwds)
...   return inner
... 
>>> def f(a, b, c, d = 3):
...   print a, b, c, d
... 
>>> runner(f, lambda: (random.randint(1,1000),))(3, 5, d = 7)
771 3 5 7
907 3 5 7
265 3 5 7
like image 107
srgerg Avatar answered Mar 07 '23 06:03

srgerg