Pass in argument to function by name dynamically

4.7k views Asked by At

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)
2

There are 2 answers

0
Zero Piraeus On BEST ANSWER

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, '!!')
0
Nouman Ahmad On

In case someone is looking for passing dynamic parameters but those parameters are not key value pair arguments. You can create a dynamic

list

and pass it like this in function call

*list

e.g.

def fun(a,b,c,d):
pass

dynamic_list = []
if True:
  dynamic_list.append(2) 

if True:
      dynamic_list.append(2)
 if True:
      dynamic_list.append(2)
 if True:
      dynamic_list.append(2)

fun(*dynamic_list)