dspjm
dspjm

Reputation: 5860

How to convert a string into an identifier in python?

Say I have a list of similar functions:

def func1(a)
    foo(a=a)

def func2(b)
    foo(b=b)
...

the only difference of them is the argument name of foo, is that a short way to define them as one function, such as passing a argument name to the functions?

Upvotes: 0

Views: 364

Answers (1)

user2357112
user2357112

Reputation: 282104

You can do it by unpacking a keyword argument dictionary:

def combined(name, value):
    foo(**{name:value})

Then combined('a', a) is equivalent to func1(a). Whether this is a good idea is a separate consideration.

Upvotes: 3

Related Questions