title: Executing a function by variable name in Python
body: <p>What I need to do is loop over a large number of different files and (try to) fetch metadata from the files.</p>
  
  <p>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.</p>
  
  <p>This is my current solution, taken from another stackoverflow thread:</p>
  
  <pre><code>try:
      getattr(modulename, funcname)(arg)
  except AttributeError:
      print 'function not found "%s" (%s)' % (funcname, arg)
  </code></pre>
  
  <p>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 ...</p>
  
  <p>What I'm looking for is more something like:</p>
  
  <pre><code>if function_exists(fun):
    execute_function(fun, arg)
  </code></pre>
  
  <p>Is there a straightforward way of doing this?</p>
  
  <p>Thanks :-)</p>