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:

#!/usr/bin/python
# 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)
        print(getattr(funcs,funcname)())

which results in the following output:


I am red
I am blue
I am green

Code: https://gist.github.com/3479054
Unrelated: This is similar to the function str2func in MATLAB.

Advertisements