Dynamically Invoke a Function in Python

In this post, I referred to an article that explains how to invoke methods dynamically (when you have the name of the method as a string object). Today I ran into a problem where I needed to do this, but the methods were not contained within a class. I just had them declared in my Python module at the root level. I believe these are called “functions” in Python.

def function1(parameter1):
    print parameter1

To invoke this dynamically, I would need to do the following:

import sys
result = getattr(sys.modules[__name__], "function1")("abc")

I guess sys.modules contains a list of all modules currently running in the system, and __name__ is the name of the current module.

Note: Thanks to this page for help on this problem.

2 Responses to “Dynamically Invoke a Function in Python”

  1. You can do this without using getattr

    fun = eval(‘function’)
    fun(“abc”)

    eval evaluates it to a function object. In python functions are callable objects, they are in a way similar to variables.

  2. globals()['function'](‘abc’)

Leave a Reply