14

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 :-)

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146

5 Answers5

27

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)
mouad
  • 67,571
  • 18
  • 114
  • 106
  • 1
    I'd wrap `func(arg)` in a `try:` and catch TypeError in case the module has an attribute `func` that isn't callable. – Wooble Mar 22 '11 at 12:37
  • @Wooble : good suggestion or he can also do : `if func and callable(func):` – mouad Mar 22 '11 at 12:40
4

The way I found is:

Code

def My_Function():
     print ("Hello World!")

FunctionName = "My_Function"

(FunctionName)()

Output

Hello World!
Wynn
  • 41
  • 1
3

The gettattr function has an optional third argument for a default value to return if the attribute does not exist, so you could use that:

fun = getattr(modulename, funcname, None)

if fun is None:
    print 'function not found "%s" (%s)' % (funcname, arg)
else
    fun(arg)
David Webb
  • 190,537
  • 57
  • 313
  • 299
-1

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

You can use this to call a function from inside a variable using this:

callable(SAVE())

This will call the function that is specified as the arg.

To use this inside a variable:

Save = callable(SAVE())
EgMusic
  • 136
  • 17
-1

You can also try

eval('func_name()')
  • Though this answer is about Python (about which, I admin, know nothing), not about PHP, but even so, I still believe that [this statement](https://stackoverflow.com/questions/5340442/php-eval-a-a#comment6029671_5340442) is true even for Python: "_Rasmus Lerdorf, the creator of PHP, once wrote that »if eval() is the answer, you're almost certainly asking the wrong question«_"! – trejder May 21 '23 at 11:41