0

Searched through stack but did not find a answer I could implement in my code.
I have a 'machine' supplied string variable -- no user input -- and need to call a function by the same name. For example:

def add(x, y):
    return x + y

the code that calls on the function:

num = function(x, y) ## where function is machine supplied string variable
                       (i.e. add, subtract, multiply, divide, etc.)

Using the 'raw' variable, function, receives str object not callable. How do I call the fxn given the string input?

0

3 Answers 3

0

If your functions are in the same module / script, use a dict:

def add(x, y):
    return x + y

# etc

OPERATORS = {
    'add': add,
    'substract': substract,
    # etc
    }

num = OPERATORS["add"](1, 2)

If they are in a distinct module, you can look them up on the module using getattr():

import operations    
num = getattr(operations, "add")(1, 2)

Bu the dict approach is still safer in that it explicitely allows only a subset of the functions.

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

Comments

0

If you want to be completely safe, you could do the following:

function_dispatcher = {'add': add, 'subtract': subtract, 'multiply', multiply, 'divide': divide}
try:
    to_call = function_dispatcher[function]
    num = to_call(x, y);
except KeyError:
    # Error code

Comments

-3

You can use eval as in eval(function(x,y)) where function is a string. X and Y may have to be built up...

command = function + "(" + x + "," + y + ")"
eval(command)

3 Comments

99.999 times out of 100, eval() is is the worst possible solution.
Tried that but still getting: TypeError: 'str' object is not callable.
I admit I like the answer supplied by @MrLeeh above better. It's cleaner and more direct. And the eval method is more error prone as you have discovered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.