tags:

views:

8864

answers:

4

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 contents are "bar". What is the best way to go about calling 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.

A: 

Well, there's:

string="bar"
exec"a=foo."+string+"()"

or maybe

exec "a=foo.%s()"%string

I'm not sure how much more elegant that is, however. But you'll be hardpressed to find a way to "execute" a string without exec or eval.

lbrandy
I didn't downvote you, but I'm guessing you pay for your last sentence: "But you'll be hardpressed to find a way to execute a string without exec or eval". It ranks up there with "640kb should be enough for everyone".
ΤΖΩΤΖΙΟΥ
Eval is evil...
ThiefMaster
+40  A: 

Assuming module 'foo' with method 'bar':

import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()

As far as that goes lines 2 and three can be compressed to:

result = getattr(foo, 'bar')()

if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-level methods, classmethods... the list goes on.

Patrick Johnmeyer
+5  A: 

Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:

m = __import__ ('foo')
func = getattr(m,'bar')
func()
HS
You should not call __import__ in this fashion, as "It mainly exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the import statement." (see Python 2.5.2 Library reference). Do "import foo" followed by "m = foo", instead.
Patrick Johnmeyer
+7  A: 
locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

jetxee