Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 410
Alfonso de la Osa Avatar asked Oct 25 '10 21:10

Alfonso de la Osa


Video Answer


1 Answers

Functions are first-class objects in Python:

def do_this():
    pass

def do_that():
    pass

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

If dct absolutely has to be a list of strings, I'd go with eval():

eval(dct[0] + "()")

It's not pretty, but switching between globals() and getattr() on the proper module can be a pain.

like image 78
Frédéric Hamidi Avatar answered Oct 14 '22 10:10

Frédéric Hamidi