1

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.

5
  • 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? Commented Jan 21, 2021 at 21:57
  • I believe your question has the answer in this question:stackoverflow.com/questions/1373164/… Commented Jan 21, 2021 at 21:58
  • 1
    You can expand dictionary key/values as keyword parameters. d = {'desired_param':5}, some_function(**d). Commented Jan 21, 2021 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? Commented Jan 21, 2021 at 21:59
  • @MarkTolonen Awesome! thanks, that's what I was looking for. Commented Jan 21, 2021 at 22:01

2 Answers 2

4

Use keyword expansion:

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

Or even shorter:

param = 'desired_param'
some_function(**{param:5})
Sign up to request clarification or add additional context in comments.

Comments

1
def some_function(**kwargs):
    print(kwargs)

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

output

{'desired_param': 5}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.