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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With