1

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! :)

0

2 Answers 2

1

Seems similar to : Passing a dictionary to a function as keyword parameters

Something like this might help:

def myfunc(a=2,b=3):
    print("a is {}\nb is {}".format(a,b))


pname = "b"
myvalue  = 5

myargs = {pname:myvalue} # set your args here as key-value pair

myfunc(**myargs)
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

This is exactly what I was looking for! Thank you! :)
@alpqs Yep! Np.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.