Julien Bernu Julien Bernu - 2 years ago 98
Python Question

how to iterate over different kwargs?

I feel like this question must have been asked before but I failed to find it, sorry if that's the case!

I have a function with different arguments like:

def f(arg1, arg2, ...,argN, kw1=0, kw2=0, kw3=0):
# some code ...

assuming I have my (compulsory) arguments defined:

arg1 = some_value_1
arg2 = some_value_2
argN = some_value_N

I want to condense some repetitive function calls like

f(arg1, arg2, ... argN, kw1=1)
f(arg1, arg2, ... argN, kw1=23)
f(arg1, arg2, ... argN, kw2=456)
f(arg1, arg2, ... argN, kw2=789)
f(arg1, arg2, ... argN, kw3='a')
f(arg1, arg2, ... argN, kw3='b')

into something looking like:

for kw_def in [kw1=1, kw1=23, kw2=456, kw2=789, kw3='a', kw3='b',...]:
f(arg1, arg2, ... argN, kw_def)

but syntactically correct. What's the right pythonic way of doing that?

Answer Source

Use dictionaries:

for kw_def in [
    {'kw1': 1},
    {'kw1': 23},
    {'kw2': 456},
    f(arg1, ..., argN, **kw_def)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download