0

I want to use a function that accepts kwargs, but the argument name is being retrieved from a separate process and is unknown before hand.

For example:

param = 'desired_param'

some_function(desired_param=5)

The problem is that I don't know the content of the param and so have to somehow pass it to some_function.

Is it possible to pass the content of the param to the function with a value?

some_function is not something I defined, so I don't have any control over it.

Mehdi Zare
  • 1,221
  • 1
  • 16
  • 32
  • So based on the TYPE of `param` you want to pass it to different parameter of the `some_function` yes? If it's `Int` then to `param_int` and if `String` then to `param_str` for example? – Jakub Szlaur Jan 21 '21 at 21:57
  • I believe your question has the answer in this question:https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – BjkOcean Jan 21 '21 at 21:58
  • 1
    You can expand dictionary key/values as keyword parameters. `d = {'desired_param':5}`, `some_function(**d)`. – Mark Tolonen Jan 21 '21 at 21:58
  • the name of the param is what I need to pass to the function, for example if it's `desired_param`, call would be `some_function(desired_param=5), but if `param` is `other`, call would be `some_function(other=5)`. Does that make sense? – Mehdi Zare Jan 21 '21 at 21:59
  • @MarkTolonen Awesome! thanks, that's what I was looking for. – Mehdi Zare Jan 21 '21 at 22:01

2 Answers2

3

Use keyword expansion:

param = 'desired_param'
d = {param:5}
some_function(**d)

Or even shorter:

param = 'desired_param'
some_function(**{param:5})
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1
def some_function(**kwargs):
    print(kwargs)

param = 'desired_param'
my_kwargs = {param:5}
some_function(**my_kwargs)

output

{'desired_param': 5}
buran
  • 13,682
  • 10
  • 36
  • 61