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
  • 75,789
  • 72
  • 163
  • 232
1

eval("function2")()

getattr(<module>, fname)()

khachik
  • 27,152
  • 7
  • 54
  • 92
0
name = 'function2'

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

eval(name)()
Jacob Schoen
  • 13,714
  • 15
  • 80
  • 101
Rosh Oxymoron
  • 19,284
  • 6
  • 40
  • 43