Function objects from Strings in Python

by Amit

Assume you have a set of functions like these:

def color_red():
    return 'I am red'

def color_green():
    return 'I am green'

def color_blue():
    return 'I am blue'

Now, in your main program, you want to call one or all of these, without creating an explicit ‘list’ of function objects. That is, you don’t want to have a list like this: [color_red, color_green, color_blue] and then simply iterate over the list and call each in turn. In some cases, you may need to construct a string literal of the function name, depending on some condition in your program. In that case, you need a way to convert a string literal to a function object.

The getattr() function can be used for this purpose. The following script demonstrates this:

# Demo of constructing function object from strings

from __future__ import print_function

# module where the functions are defined
import funcs

# entry point when executed
if __name__=='__main__':
    colors = ['red','blue','green']
    for color in colors:
        funcname = 'color_{0:s}'.format(color)

which results in the following output:

I am red
I am blue
I am green

Unrelated: This is similar to the function str2func in MATLAB.