Calling a function of a module from a string with the function's name in Python
<p>What is the best way to go about calling a function given a string with the function's name in a Python program.  For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>

<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> 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.</p>

<p>Assuming module <code>foo</code> with method <code>bar</code>:</p>

<pre><code>import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()
</code></pre>

<p>As far as that goes, lines 2 and 3 can be compressed to:</p>

<pre><code>result = getattr(foo, 'bar')()
</code></pre>

<p>if that makes more sense for your use case.  You can use <code>getattr</code> in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.</p>
