Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

Passing a variable name as a parameter to a function in Python

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.

question from:https://stackoverflow.com/questions/65836280/passing-a-variable-name-as-a-parameter-to-a-function-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use keyword expansion:

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

Or even shorter:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...