0

Is it possible for one function to take as an argument the name of one of the optional arguments of a second function then call the second function with the optional argument set to the value of some variable in the first function?

Code (that obviously doesn't work)

def foo(a=1,b=2,c=3):
    d = a + b + c
    return d

def bar(variable):
    z = get_user_input()
    e = foo(variable = z)
    return e

print(bar(a))

The desired result is for bar to call foo(a=z) and print whatever z+2+3 is. Of course Python doesn't know what (a) is here. My guess is that I can somehow reference the list of arguments of foo() , but I am stumped as to how you might do that.

1
  • Do you mean to call bar with the name of the variable as a string: print(bar('a'))? Your code currently would raise an error Commented Oct 13, 2021 at 2:57

1 Answer 1

1

Maybe try the code snippet below

def foo(a=1,b=2,c=3):
    d = a + b + c
    return d

def bar(variable: str):
    z = int(input())
    e = foo(**{variable: z})
    return e

# variable name should be defined as string
print(bar("a"))

The ** parses all arbitrary arguments on dict, in this case is a. Be careful tho, as if passing wrong variable name (differ from a, b or c) will result raising error.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for. Thank you!

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.