Search code examples
pythonfunctiondictionarysignature

Use dict values as kwargs in function that have not compatible signature


I have a single structure that is being used as a limit factor for multiple generators.

The structure looks like this:

my_dict = {
  "a": {
    "low": 0,
    "high": 1,
  },
  "b": {
    "low": 0,
    "high": 2,
  },
}

And generators looks like this:

def gen_1(low: float, high: float):
    return random.uniform(low, high)

def gen_2(lower_bound: float, higher_bound: float):
    return random.uniform(lower_bound, higher_bound)

Generators have a different signature and cannot be changed (3rd party libraries).

For me it is really convenient to use kwargs and when it comes to the gen_1() I can do something like this:

value = gen_1(**my_dict["a"])

Unfortunately, I cannot use the second generator in the same fashion and am forced to explicitly set these arguments:

value = gen_2(lower_bound=my_dict["a"]["low"], higher_bound=my_dict["a"]["high"])

Is it possible to somehow map these key values 'on the fly' while using kwargs?


Solution

  • One possibility could be to use operator.itemgetter and unpacking its output:

    from operator import itemgetter
    
    gen_1(*itemgetter('low', 'high')(my_dict['a']))
    
    gen_2(*itemgetter('low', 'high')(my_dict['a']))