This is an old copy of the Python FAQ. The information here may be outdated.

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

 

A Django site. rendered by a django application. hosted by webfaction.