Run python function several times with different arguments

Hi, I need to have a function that will take a function and return a function that will run this argument function, for example. 1000 times and each time evaluate his argument. I have something like this:

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

But it looks like a call like this: runner(f)(random.randint(1,UPPER_BOUND)) works f 1000 times with the same argument. How to do it right?

+4
source share
3 answers

The problem you are facing is that random.randint(1,UPPER_BOUND) is evaluated once during the call to the inner() function returned by runner() . You need to postpone the assessment until the end.

You can 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 every time the original function f called. Also note that callable must return a sequence type, such as a tuple or list.

Edit: if you need to pass other arguments to f , you can do it 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 
+7
source

You will need to move the random.randint calculation to the defintion function:

For example, something like this should start you off, @ is the decorator syntax, which you can read here here if you are not familiar with it. It's shameless to steal the hello example from another post:

 import random UPPER_BOUND = 1000 def runner(fn): def wrapped(): for i in range(0,10): stuff = random.randint(1,UPPER_BOUND) print(str(stuff) + ': ' + fn()) return wrapped @runner def hello(): return 'hello world' if __name__=='__main__': hello() 

Edit: Also see here to understand why your random case is triggered only once (during definition), so your function gets the same argument every time.

+1
source

You should put a random.randit call inside the loop:

 def runner(function): def inner(callable, args=()): for i in xrange(1000): function(callable(*args)) return inner 

And you can call the runner:

 runner(f)(random.randint, args=(1, UPPER_BOND)) 

It seemed to me what you were trying to do (and not related to ugly lambdas).

+1
source

Source: https://habr.com/ru/post/1391177/


All Articles