We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I use strings to call functions/methods?

The best and most robust technique is to use a dictionary that maps strings to function objects, as described in this article:

why-isn-t-there-a-switch-or-case-statement-in-python

Alternative solutions include using locals or eval to resolve the function name:

def myFunc():
    print "hello"

fname = "myFunc"

f = locals()[fname]
f()

f = eval(fname)
f()

These are slower than using a custom dictionary, and also more dangerous. The locals approach makes it possible to call any function in the local scope, while eval makes it possible to execute arbitrary code. Only use these if you know exactly what you’re doing.

CATEGORY: programming