Interview Questions

How do I use strings to call functions/methods?

Python Questions and Answers

(Continued from previous question...)

How do I use strings to call functions/methods?

There are various techniques.

* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

def a():

def b():

dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs

dispatch[get_input()]() # Note trailing parens to call function
Use the built-in function getattr():

import foo
getattr(foo, 'bar')()

Note that getattr() works on any object, including classes, class instances, modules, and so on.

This is used in several places in the standard library, like this:

class Foo:
def do_foo(self):
def do_bar(self):

f = getattr(foo_instance, 'do_' + opname)

Use locals() or eval() to resolve the function name:

def myFunc():
print "hello"

fname = "myFunc"

f = locals()[fname]

f = eval(fname)

Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.

(Continued on next question...)

Other Interview Questions