Search code examples
pythonfunctiondynamicoptional-arguments

How to convert a string to optional argument name in Python function?


I am new to Python and would like to know how to pass an optional argument name “dynamically” in a function using a string stored in some variable.

This is my function:

def my_func(arg1=4 arg2=8):
   print(arg1 * arg2)

And this what my code looks like now:

param_name = “arg1”
param_value = 5

if param_name == “arg1”:
   my_func(arg1=param_value)
elif param_name == “arg2”:
   my_func(arg2=param_value)

My question is if it’s possible to simplify the above code without the if/elif to something like this:

param_name = “arg1”
param_value = 5

my_func(eval(param_name) = param_value)

PS: I know that this is not how to use eval() and that using eval is insecure and considered a bad practice in most cases, so the code is only to illustrate that I need to pass an optional parameter name “dynamically” with a string value from a previously defined variable.

How to do that in Python (and in the most secure way)?

Thanks in advance! :)


Solution

  • Here you go. Try using the **functions in python.

    def my_func(arg1=4, arg2=8):
       print(arg1 * arg2)
    
    param = {"arg1": 5} # this is a dictionary
    
    my_func(**param)
    

    This prints:40

    The best part is, you can actually specify many arguments at the same time!

    def my_func(arg1=4, arg2=8):
       print(arg1 * arg2)
    
    params = {"arg1": 5, "arg2":10} # this is a dictionary
    
    my_func(**params)
    

    This prints: 50