1

I am looking to figure out how I can dynamically call certain functions based on user input. For example, I have the following code that just does simple math based on a series of keyword arguments.

def calculate(**kwargs):
    operation = kwargs.get("operation")

    def add(num1,num2,msg="The result is"):
          return f"{msg} {float(num1 + num2)}" if kwargs.get("make_float") else f"{msg} {float(num1 + num2)}"

    def sub(num1,num2,msg="The result is"):
          return f"{msg} {float(num1 - num2)}" if kwargs.get("make_float") else f"{msg} {num1 - num2}"

    def multiply(num1,num2,msg="The result is"):
          return f"{msg} {float(num1 * num2)}" if kwargs.get("make_float") else f"{msg} {(num1 * num2)}"

    def divide(num1,num2,msg="The result is"):
          return f"{msg} {float(num1 / num2)}" if kwargs.get("make_float") else f"{msg} {(num1 / num2)}"

    return operation(kwargs.get("first"),kwargs.get("second"),kwargs.get("message"))

print(calculate(make_float=False, operation='add', message='You just added', first=2, second=4))

I know there are better ways to do a calculator of course, but the point here is I want to try and avoid using a bunch of if/elses to check and see what function to run between add/sub/divide/multiply. I thought I could save it into a variable called "operation" and use that to call the proper function, but that will not work as a string isn't callable.

Essentially I want to be able to dynamically call a function based on user input (assuming the user input is exactly the name of the function) but I am unsure how.

1 Answer 1

2

Since functions are objects in Python, it's easy to make a dictionary pairing keywords with functions.

action_dict = {'add': add,
               'sub': sub,
               # ...
              }

if operation in action_dict:
    action_dict[operation](num1, num2)
Sign up to request clarification or add additional context in comments.

1 Comment

Right that makes sense. Thanks for the help

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.