1

I'd like to run a function that is identified by a string.

toRun = 'testFunction'

def testFunction():
    log.info('In the function');

run(toRun)

Where run would be whatever command I need to use. I've tried with exec/eval without much luck.

Scott Robinson
  • 583
  • 1
  • 7
  • 23
  • possible duplicate of [Calling a function of a module from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – Hacketo Jun 15 '15 at 08:53

4 Answers4

3

locals returns a dict containing references in the current scope

locals()[toRun]()
GP89
  • 6,600
  • 4
  • 36
  • 64
2

Better use a dictionary that maps strings to functions.

def func1():
    print("in function 1")

def func2():
    print("in function 2")


functions = {
    "func1": func1,
    "func2": func2
}

# Get function by name.
the_func = functions["func1"]
# Execute it.
the_func()
2

The build in function getattr() can be used to return an named attribute of the object passed as argument.

Example

>>> import sys
>>> def function():
...     print 'hello'
... 
>>> fun_object = getattr( sys.modules[ __name__ ], 'function')
>>> fun_object()
hello

What it does

  • sys.modules[ __name__ ] returns the current module object.

  • getattr( sys.modules[ __name__ ], 'function') returns an attribute by the name function of the object, sys.modules[ __name__ ] which is the current object.

  • fun_object() calls the returned function.
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0

You can use eval

eval("testFunction()") # must have brackets in order to call the function

Or you could

toRun += "()"

eval("eval(toRun)")
xyres
  • 20,487
  • 3
  • 56
  • 85
  • 1
    You *can* use `eval`. But don't do it if it isn't absolutely necessary. –  Jun 15 '15 at 08:55