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?

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118

3 Answers3

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.

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
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
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
-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)
Ron Norris
  • 2,642
  • 1
  • 9
  • 13