Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function on all possible combinations of parameters

I have sets of values that I want to apply as parameters to a function:

params = {
    'a': [1, 2, 3],
    'b': [5, 6, 7],
    'x': [None, 'eleven', 'f'],
    # et cetera
}

I want to run myfunc() with all possible combinations, so myfunc(a=1, b=5, x=None ...), myfunc(a=2, b=5, x=None ...) ... myfunc(a=3, b=7, x='f' ...). Is there something (for example in itertools) that can help? I thought about using itertools.product() but that doesn't keep the names of the parameters and just gives me tuples of the combinations.

like image 933
Bluefire Avatar asked Jul 03 '17 14:07

Bluefire


2 Answers

You can use itertools.product to get all combinations of arguments:

>>> import itertools
>>> for xs in itertools.product([1,2], [5,6], ['eleven', 'f']):
...     print(xs)
... 
(1, 5, 'eleven')
(1, 5, 'f')
(1, 6, 'eleven')
(1, 6, 'f')
(2, 5, 'eleven')
(2, 5, 'f')
(2, 6, 'eleven')
(2, 6, 'f')

With Argument list unpacking, you can call myfunc with all combinations of keyword arguments:

params = {
    'a': [1, 2, 3],
    'b': [5, 6, 7],
    'x': [None, 'eleven', 'f'],
}

def myfunc(**args):
    print(args)

import itertools
keys = list(params)
for values in itertools.product(*map(params.get, keys)):
    myfunc(**dict(zip(keys, values)))

output:

{'a': 1, 'x': None, 'b': 5}
{'a': 1, 'x': None, 'b': 6}
{'a': 1, 'x': None, 'b': 7}
{'a': 1, 'x': 'eleven', 'b': 5}
{'a': 1, 'x': 'eleven', 'b': 6}
{'a': 1, 'x': 'eleven', 'b': 7}
{'a': 1, 'x': 'f', 'b': 5}
...
like image 127
falsetru Avatar answered Sep 21 '22 15:09

falsetru


I developed combu which is that solution.

  1. Install combu

pip install combu

  1. Use combu
# Case 1: Directly call
import combu

for res, param in combu.execute(myfunc, params):
    print(res, params)

# Case 2: Use class
from combu import Combu

comb = Combu(myfunc)

for res, param in comb.execute(params):
    print(res, params)
like image 25
takelushi Avatar answered Sep 22 '22 15:09

takelushi