0

I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python?

Example:

In File 1

def function1: ...
def function2: ...
def function3: ...

In File 2

functionname = "function2"

I need to call the function2 from the File1 from this file

  • 2
    possible duplicate of [Calling a Function From a String With the Function's Name in Python](http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python) – Jim Brissom Nov 18 '10 at 11:34

3 Answers3

6
myfunction = getattr(mymodule, functionname)
myfunction()
froadie
  • 79,995
  • 75
  • 166
  • 235
1

eval("function2")()

getattr(<module>, fname)()

khachik
  • 28,112
  • 9
  • 59
  • 94
0
name = 'function2'

assert re.match('^(?i)[_a-z][_a-z0-9]*$', name)

eval(name)()
Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
Rosh Oxymoron
  • 20,355
  • 6
  • 41
  • 43