Search code examples
pythonpython-3.xdynamicparameter-passingargument-unpacking

Pass in argument to function by name dynamically


Is it possible to dynamically set the name of an argument being passed into a function?

like this:

def func(one=None, two=None, three=None, four=None):
    ...

params = ("one","two","three","four",)
for var in params:
    tmp = func(var=value)

Solution

  • Yes, with keyword argument unpacking:

    def func(one=None, two=None, three=None, four=None):
        return (one, two, three, four)
    
    params = ("one", "two", "three", "four")
    for var in params:
        tmp = func(**{var: "!!"})
        print(tmp)
    

    Output:

    ('!!', None, None, None)
    (None, '!!', None, None)
    (None, None, '!!', None)
    (None, None, None, '!!')