Executing a function by variable name in Python

The way I found is:

Code

def My_Function():
     print ("Hello World!")

FunctionName = "My_Function"

(FunctionName)()

Output

Hello World!

You can do :

func = getattr(modulename, funcname, None):
if func:
    func(arg)

Or maybe better:

try:
    func = getattr(modulename, funcname)
except AttributeError:
    print 'function not found "%s" (%s)' % (funcname, arg)
else:
    func(arg)

The gettattr function has an optional third argument for a default value to return if the attribute does not exist, so you could use that:

fun = getattr(modulename, funcname, None)

if fun is None:
    print 'function not found "%s" (%s)' % (funcname, arg)
else
    fun(arg)

Tags:

Python