Executing a function by variable name in Python

I need to loop through a lot of different files and (try) extract the metadata from the files.

I can make a big if ... elif ... and check for each extension, but I think it would be much easier to store the extension in a variable, check if there is a function with that name and execute it.

This is my current solution, taken from another stackoverflow:

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

The problem with this: If the underlying function raises the AttributeError attribute, it is logged as a "function not found" error. I can add try ... besides blocks to all functions, but that would not be particularly nice ...

What I'm looking for is more like:

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

Is there an easy way to do this?

Thanks: -)

+7
source share
3 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) 
+22
source

The gettattr function has an additional third argument for the default return value if the attribute does not exist, so you can use this

 fun = getattr(modulename, funcname, None) if fun is None: print 'function not found "%s" (%s)' % (funcname, arg) else fun(arg) 
+3
source

Like @mouad, callable(function) can call a function.

You can use this to call a function from within a variable using the following command:

 callable(SAVE()) 

This will call the function specified as arg.

To use this inside a variable:

 Save = callable(SAVE()) 
0
source

All Articles