Execute function on all possible combinations of parameters
I developed combu which is that solution.
- Install combu
pip install combu
- 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)
Ordering of .keys
and .values
are guaranteed across all Python versions (unless dict is altered which does not happen here), so this might be a bit trivial:
from itertools import product
for vals in product(*params.values()):
myfunc(**dict(zip(params, vals)))
You can find the gurantee in the docs:
If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.
Demo:
for vals in product(*params.values()):
print(dict(zip(params, vals)))
{'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}
{'a': 1, 'x': 'f', 'b': 6}
{'a': 1, 'x': 'f', 'b': 7}
...
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}
...