I have the following problem: I would like to provide a simple function which iterates over a list of parameter set and does the same action for all set. The idea is that the either scalar values, or any iterable is passed as kwarg to the function, which then generates each set of kwargs, and then calls the action on them.
def simple_function(**kwargs):
list_of_kwargs = convert_kwargs(kwargs)
return [my_action(**kwargs_set) for kwargs_set in list_of_kwargs]
So provided that, I find it hard to implement convert_kwargs
to be efficient and generic. Some example test cases I need to fulfill:
class ConvertParamsTestCase(unittest.TestCase):
def test_convert_kwargs_no_list(self):
kwargs = {'arg1': 1, 'arg2': "string", 'arg3': None}
self.assertDictEqual(kwargs, convert_kwargs(kwargs))
def test_convert_kwargs_all_lists(self):
kwargs = {'arg1': [1, 2], 'arg2': ["string", "str"], 'arg3': [None, None]}
expected = [{'arg1': 1, 'arg2': "string", 'arg3': None}, {'arg1': 2, 'arg2': "str", 'arg3': None}]
self.assertListEqual(expected, convert_kwargs(kwargs))
def test_convert_kwargs_one_is_string(self):
kwargs = {'arg1': [1, 2], 'arg2': "string", 'arg3': [None, None]}
expected = [{'arg1': 1, 'arg2': "string", 'arg3': None}, {'arg1': 2, 'arg2': "string", 'arg3': None}]
self.assertListEqual(expected, convert_kwargs(kwargs))
def test_convert_kwargs_one_is_iterator(self):
kwargs = {'arg1': range(1, 3), 'arg2': "string", 'arg3': [None, None]}
expected = [{'arg1': 1, 'arg2': "string", 'arg3': None}, {'arg1': 2, 'arg2': "string", 'arg3': None}]
self.assertListEqual(expected, convert_kwargs(kwargs))
I have checked this without success: list of dicts to/from dict of lists
My main problems are that:
- strings are iterables
- I cannot check the length of a generator only by evaluating it
I would greatly appreciate any ideas!