What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Assuming module
foo
with methodbar
:As far as that goes, lines 2 and 3 can be compressed to:
if that makes more sense for your use case. You can use
getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.or
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:
Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:
For example:
And, if not a class:
Given a string, with a complete python path to a function, this is how I went about getting the result of said function:
The best answer according to the Python programming FAQ would be:
The answer (I hope) no one ever wanted
Eval like behavior
Why not add auto-importing
In case we have extra dictionaries we want to check
We need to go deeper
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:
Try this. While this still uses eval, it only uses it to summon the function from the current context. Then, you have the real function to use as you wish.
The main benefit for me from this is that you will get any eval-related errors at the point of summoning the function. Then you will get only the function-related errors when you call.
none of what was suggested helped me. I did discover this though.
I am using python 2.66
Hope this helps
As this question How to dynamically call methods within a class using method-name assignment to a variable [duplicate] marked as a duplicate as this one, I am posting a related answer here:
The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:
This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you're using Windows, change
clear
tocls
, Linux and Mac users leave as is for example) or just execute it, respectively.