Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function by variable name in Python

Tags:

python

What I need to do is loop over a large number of different files and (try to) fetch metadata from the files.

I can make a large if...elif... and test for every extension, but I think it would be much easier to store the extension in a variable, check if a function with that name exists, and execute it.

This is my current solution, taken from another stackoverflow thread:

try:
    getattr(modulename, funcname)(arg)
except AttributeError:
    print 'function not found "%s" (%s)' % (funcname, arg)

There is a problem with this: If the underlying function raises an AttributeError, this is registered as a "function not found" error. I can add try...except blocks to all functions, but that would not be particularly pretty either ...

What I'm looking for is more something like:

if function_exists(fun):
  execute_function(fun, arg)

Is there a straightforward way of doing this?

Thanks :-)

like image 719
Martin Tournoij Avatar asked Mar 22 '11 12:03

Martin Tournoij


People also ask

How do you call a function from a variable in Python?

To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.

How do you call a function by its string name in Python?

Use eval() to call a function by its name as a string Call eval(string) with string as the function name and "()" .

How do you call a function in Python?

Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. >>> greet('Paul') Hello, Paul.

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


1 Answers

You can do :

func = getattr(modulename, funcname, None):
if func:
    func(arg)

Or maybe better:

try:
    func = getattr(modulename, funcname)
except AttributeError:
    print 'function not found "%s" (%s)' % (funcname, arg)
else:
    func(arg)
like image 70
mouad Avatar answered Oct 09 '22 17:10

mouad