Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function of a module by using its name (a string)

Tags:

python

object

What is the best way to go call 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.

like image 424
ricree Avatar asked Aug 06 '08 03:08

ricree


People also ask

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How can I call a function given its name as a string Python?

Use locals() and globals() to Call a Function From a String in Python.

How do you call a function in a module?

To call a function module, use the CALL FUNCTIONstatement: CALL FUNCTION module [EXPORTING f 1 = a 1 ... f n = a n ] [IMPORTING f 1 = a 1 ... f n = a n ] [CHANGING f 1 = a 1 ...

How can I call a function given its name as a string in C?

Put all the functions you want to select from into a dll, then use dlsym (or GetProcAddress on Windows, or whatever other API your system offers) to get the function pointer by name, and call using that.


2 Answers

Assuming module foo with method bar:

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

You could shorten lines 2 and 3 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, class methods... the list goes on.

like image 88
Patrick Johnmeyer Avatar answered Oct 17 '22 06:10

Patrick Johnmeyer


locals()["myfunction"]() 

or

globals()["myfunction"]() 

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

like image 29
sastanin Avatar answered Oct 17 '22 06:10

sastanin