aconkey aconkey - 28 days ago 7
Python Question

python - Call a function with a specified variable name assigning value to that variable

I want to be able to pass in the name of variable to a function, and have that function call another function that calls the first function with a particular value assigned to the variable name. For example:

# function with argument 'arg2'
def foo(arg1=None, arg2=None, arg3=None):
print arg2

# function that calls foo with a value assigned to designated variable
def bar(var, value):
foo(var=value)


So that when I call

> foo(arg2, 10)


I get the output

Output: 10


How is this done?

Answer

You can't do that, because it makes no sense; the name arg2 would always refer to whatever the value of that variable is.

You can however pass the string "arg2", and use kwargs to call the function:

def bar(var, value):
    foo(**{var: value})

although you would be better off doing this directly and removing the need for bar altogether.

Comments