What's the way to call a function dynamically in Python?

python

Solution

Functions are first class objects. So like this:

def do_this():
    print "In do_this"

def do_that():
    print "In do_that"

dct = [do_this, do_that]
dct[0]()

If you really want to call them from a string list you can use globals():

dct = ['do_this', 'do_that']
globals()[dct[0]]()

But I would suggest that using globals() (or locals()) probably isn't the right way to solve your problem. Grok the python way: `>>> import this`

Problem

I would like to do something like: ``` dct = ['do_this', 'do_that'] dct[0]() // call do_this ``` But you can't call the string as a function (will get an error). How can I achieve this without switching and without using a list of lambdas or functions? Explicitly I want to refer the function by name.

Original source