Ryan Loggerythm
Ryan Loggerythm

Reputation: 3314

passing function parameter names as strings

I'm working with an API that has dozens of parameters in a given function:

api.update_customer(a='', b='', c='', ..., x='', y='', z='')

I'll only need to update one or a few parameters when I call it, for instance:

api.update_customer(email='[email protected]')

...but I won't know in advance which object needs updating (maybe email, maybe phone number, etc).

How can I build a wrapper around this call so I can pass in both the parameter name and its new value?

def update_customer_details(key, value):
    api.update_customer(key=value)

Upvotes: 0

Views: 73

Answers (3)

kederrac
kederrac

Reputation: 17322

you can try:

api.update_customer(field='my_field', value='my_value', *args, **kwrgs) 

Upvotes: 0

Chrismon Chin
Chrismon Chin

Reputation: 429

To expand on Daniel Roseman answer for an example on how it gets used:

def test2(x=None):
    print(x)

def test(**kwarg):
    test2(**kwarg)

test(x=5)

output: 5

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599530

You don't need to write a wrapper. Just pass a dict using keyword expansion.

params = {'email': '[email protected]'}
api.update_customer(**params)

Upvotes: 4

Related Questions