<p>How do I call a function, using a string with the function's name? For example:</p>
<pre><code>import foo
func_name = &quot;bar&quot;
call(foo, func_name)  # calls foo.bar()
</code></pre>

[{'answer_id': 3071, 'author': 'Patrick Johnmeyer', 'author_id': 363, 'author_profile': 'https://Stackoverflow.com/users/363', 'pm_score': 12, 'selected': True, 'text': '<p>Given a module <code>foo</code> with method <code>bar</code>:</p>\n<pre><code>import foo\nbar = getattr(foo, \'bar\')\nresult = bar()\n</code></pre>\n<p><a href="https://docs.python.org/library/functions.html#getattr" rel="noreferrer"><code>getattr</code></a> can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.</p>\n'}, {'answer_id': 4605, 'author': 'HS.', 'author_id': 618, 'author_profile': 'https://Stackoverflow.com/users/618', 'pm_score': 9, 'selected': False, 'text': '<p>Based on <a href="https://stackoverflow.com/a/3071/365102">Patrick\'s solution</a>, to get the module dynamically as well, import it using:</p>\n<pre><code>module = __import__(\'foo\')\nfunc = getattr(module, \'bar\')\nfunc()\n</code></pre>\n'}, {'answer_id': 834451, 'author': 'sastanin', 'author_id': 25450, 'author_profile': 'https://Stackoverflow.com/users/25450', 'pm_score': 10, 'selected': False, 'text': '<ul>\n<li><p>Using <a href="http://docs.python.org/library/functions.html#locals" rel="noreferrer"><code>locals()</code></a>, which returns a dictionary with the current local symbol table:</p>\n<pre><code>locals()[&quot;myfunction&quot;]()\n</code></pre>\n</li>\n<li><p>Using <a href="http://docs.python.org/library/functions.html#globals" rel="noreferrer"><code>globals()</code></a>, which returns a dictionary with the global symbol table:</p>\n<pre><code>globals()[&quot;myfunction&quot;]()\n</code></pre>\n</li>\n</ul>\n'}, {'answer_id': 9272378, 'author': 'trubliphone', 'author_id': 1060339, 'author_profile': 'https://Stackoverflow.com/users/1060339', 'pm_score': 5, 'selected': False, 'text': '<p>For what it\'s worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:</p>\n\n<pre><code>myFnName  = "MyFn"\nmyAppName = "MyApp"\napp = sys.modules[myAppName]\nfn  = getattr(app,myFnName)\n</code></pre>\n'}, {'answer_id': 12025554, 'author': 'Sourcegeek', 'author_id': 1609832, 'author_profile': 'https://Stackoverflow.com/users/1609832', 'pm_score': 7, 'selected': False, 'text': "<p>Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:</p>\n\n<pre><code># Get class from globals and create an instance\nm = globals()['our_class']()\n\n# Get the function (from the instance) that we need to call\nfunc = getattr(m, 'function_name')\n\n# Call it\nfunc()\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>class A:\n    def __init__(self):\n        pass\n\n    def sampleFunc(self, arg):\n        print('you called sampleFunc({})'.format(arg))\n\nm = globals()['A']()\nfunc = getattr(m, 'sampleFunc')\nfunc('sample arg')\n\n# Sample, all on one line\ngetattr(globals()['A'](), 'sampleFunc')('sample arg')\n</code></pre>\n\n<p>And, if not a class:</p>\n\n<pre><code>def sampleFunc(arg):\n    print('you called sampleFunc({})'.format(arg))\n\nglobals()['sampleFunc']('sample arg')\n</code></pre>\n"}, {'answer_id': 14072943, 'author': 'Natdrip', 'author_id': 1112523, 'author_profile': 'https://Stackoverflow.com/users/1112523', 'pm_score': 4, 'selected': False, 'text': '<p>none of what was suggested helped me. I did discover this though.</p>\n\n<pre><code>&lt;object&gt;.__getattribute__(&lt;string name&gt;)(&lt;params&gt;)\n</code></pre>\n\n<p>I am using python 2.66 </p>\n\n<p>Hope this helps</p>\n'}, {'answer_id': 19393328, 'author': 'ferrouswheel', 'author_id': 272238, 'author_profile': 'https://Stackoverflow.com/users/272238', 'pm_score': 7, 'selected': False, 'text': "<p>Given a string, with a complete python path to a function, this is how I went about getting the result of said function:</p>\n\n<pre><code>import importlib\nfunction_string = 'mypackage.mymodule.myfunc'\nmod_name, func_name = function_string.rsplit('.',1)\nmod = importlib.import_module(mod_name)\nfunc = getattr(mod, func_name)\nresult = func()\n</code></pre>\n"}, {'answer_id': 22959509, 'author': '00500005', 'author_id': 1356953, 'author_profile': 'https://Stackoverflow.com/users/1356953', 'pm_score': 6, 'selected': False, 'text': '<p>The answer (I hope) no one ever wanted</p>\n\n<p>Eval like behavior</p>\n\n<pre><code>getattr(locals().get("foo") or globals().get("foo"), "bar")()\n</code></pre>\n\n<p>Why not add auto-importing</p>\n\n<pre><code>getattr(\n    locals().get("foo") or \n    globals().get("foo") or\n    __import__("foo"), \n"bar")()\n</code></pre>\n\n<p>In case we have extra dictionaries we want to check</p>\n\n<pre><code>getattr(next((x for x in (f("foo") for f in \n                          [locals().get, globals().get, \n                           self.__dict__.get, __import__]) \n              if x)),\n"bar")()\n</code></pre>\n\n<p>We need to go deeper</p>\n\n<pre><code>getattr(next((x for x in (f("foo") for f in \n              ([locals().get, globals().get, self.__dict__.get] +\n               [d.get for d in (list(dd.values()) for dd in \n                                [locals(),globals(),self.__dict__]\n                                if isinstance(dd,dict))\n                if isinstance(d,dict)] + \n               [__import__])) \n        if x)),\n"bar")()\n</code></pre>\n'}, {'answer_id': 40219576, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>The best answer according to the <a href="https://docs.python.org/3/faq/programming.html#how-do-i-use-strings-to-call-functions-methods" rel="noreferrer">Python programming FAQ</a> would be:</p>\n\n<pre><code>functions = {\'myfoo\': foo.bar}\n\nmystring = \'myfoo\'\nif mystring in functions:\n    functions[mystring]()\n</code></pre>\n\n<blockquote>\n  <p>The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct</p>\n</blockquote>\n'}, {'answer_id': 41024742, 'author': 'tvt173', 'author_id': 701803, 'author_profile': 'https://Stackoverflow.com/users/701803', 'pm_score': 5, 'selected': False, 'text': "<p>Try this. While this still uses eval, it only uses it to <em>summon the function from the current context</em>. Then, you have the real function to use as you wish.</p>\n\n<p>The main benefit for me from this is that you will get any eval-related errors at the point of summoning the function. Then you will get <em>only</em> the function-related errors when you call.</p>\n\n<pre><code>def say_hello(name):\n    print 'Hello {}!'.format(name)\n\n# get the function by name\nmethod_name = 'say_hello'\nmethod = eval(method_name)\n\n# call it like a regular function later\nargs = ['friend']\nkwargs = {}\nmethod(*args, **kwargs)\n</code></pre>\n"}, {'answer_id': 55363812, 'author': 'Serjik', 'author_id': 546822, 'author_profile': 'https://Stackoverflow.com/users/546822', 'pm_score': 4, 'selected': False, 'text': '<p>As this question <a href="https://stackoverflow.com/questions/16642145/how-to-dynamically-call-methods-within-a-class-using-method-name-assignment-to-a">How to dynamically call methods within a class using method-name assignment to a variable [duplicate]</a> marked as a duplicate as this one, I am posting a related answer here:</p>\n\n<p>The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:</p>\n\n<pre><code>class MyClass:\n    def __init__(self, i):\n        self.i = i\n\n    def get(self):\n        func = getattr(MyClass, \'function{}\'.format(self.i))\n        func(self, 12)   # This one will work\n        # self.func(12)    # But this does NOT work.\n\n\n    def function1(self, p1):\n        print(\'function1: {}\'.format(p1))\n        # do other stuff\n\n    def function2(self, p1):\n        print(\'function2: {}\'.format(p1))\n        # do other stuff\n\n\nif __name__ == "__main__":\n    class1 = MyClass(1)\n    class1.get()\n    class2 = MyClass(2)\n    class2.get()\n</code></pre>\n\n<blockquote>\n  <p>Output (Python 3.7.x)</p>\n  \n  <p>function1: 12 </p>\n  \n  <p>function2: 12</p>\n</blockquote>\n'}, {'answer_id': 57696855, 'author': 'Number File', 'author_id': 11530007, 'author_profile': 'https://Stackoverflow.com/users/11530007', 'pm_score': -1, 'selected': False, 'text': '<p>This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you\'re using Windows, change <code>clear</code> to <code>cls</code>, Linux and Mac users leave as is for example) or just execute it, respectively.</p>\n\n<pre><code>eval("os.system(\\"clear\\")")\nexec("os.system(\\"clear\\")")\n</code></pre>\n'}, {'answer_id': 62672406, 'author': '정도유', 'author_id': 5532667, 'author_profile': 'https://Stackoverflow.com/users/5532667', 'pm_score': 3, 'selected': False, 'text': '<p><code>getattr</code> calls method by name from an object.\nBut this object should be parent of calling class.\nThe parent class can be got by <code>super(self.__class__, self)</code></p>\n<pre class="lang-py prettyprint-override"><code>class Base:\n    def call_base(func):\n        &quot;&quot;&quot;This does not work&quot;&quot;&quot;\n        def new_func(self, *args, **kwargs):\n            name = func.__name__\n            getattr(super(self.__class__, self), name)(*args, **kwargs)\n        return new_func\n\n    def f(self, *args):\n        print(f&quot;BASE method invoked.&quot;)\n\n    def g(self, *args):\n        print(f&quot;BASE method invoked.&quot;)\n\nclass Inherit(Base):\n    @Base.call_base\n    def f(self, *args):\n        &quot;&quot;&quot;function body will be ignored by the decorator.&quot;&quot;&quot;\n        pass\n\n    @Base.call_base\n    def g(self, *args):\n        &quot;&quot;&quot;function body will be ignored by the decorator.&quot;&quot;&quot;\n        pass\n\nInherit().f() # The goal is to print &quot;BASE method invoked.&quot;\n</code></pre>\n'}, {'answer_id': 62937980, 'author': 'Lukas', 'author_id': 10257810, 'author_profile': 'https://Stackoverflow.com/users/10257810', 'pm_score': 4, 'selected': False, 'text': "<p>Although getattr() is elegant (and about 7x faster) method, you can get return value from the function (local, class method, module) with eval as elegant as <code>x = eval('foo.bar')()</code>. And when you implement some error handling then quite securely (the same principle can be used for getattr). Example with module import and class:</p>\n<pre><code># import module, call module function, pass parameters and print retured value with eval():\nimport random\nbar = 'random.randint'\nrandint = eval(bar)(0,100)\nprint(randint) # will print random int from &lt;0;100)\n\n# also class method returning (or not) value(s) can be used with eval: \nclass Say:\n    def say(something='nothing'):\n        return something\n\nbar = 'Say.say'\nprint(eval(bar)('nice to meet you too')) # will print 'nice to meet you' \n</code></pre>\n<p>When module or class does not exist (typo or anything better) then NameError is raised. When function does not exist, then AttributeError is raised. This can be used to handle errors:</p>\n<pre><code># try/except block can be used to catch both errors\ntry:\n    eval('Say.talk')() # raises AttributeError because function does not exist\n    eval('Says.say')() # raises NameError because the class does not exist\n    # or the same with getattr:\n    getattr(Say, 'talk')() # raises AttributeError\n    getattr(Says, 'say')() # raises NameError\nexcept AttributeError:\n    # do domething or just...\n    print('Function does not exist')\nexcept NameError:\n    # do domething or just...\n    print('Module does not exist')\n</code></pre>\n"}, {'answer_id': 67982516, 'author': 'Bowen 404', 'author_id': 7266363, 'author_profile': 'https://Stackoverflow.com/users/7266363', 'pm_score': 2, 'selected': False, 'text': '<p>i\'m facing the similar problem before, which is to convert a string to a function. <strong>but i can\'t use <code>eval()</code> or <code>ast.literal_eval()</code>, because i don\'t want to execute this code immediately.</strong></p>\n<p>e.g. i have a string <code>&quot;foo.bar&quot;</code>, and i want to assign it to <code>x</code> as a function name instead of a string, which means i can call the function by <code>x()</code> <strong>ON DEMAND</strong>.</p>\n<p>here\'s my code:</p>\n<pre class="lang-py prettyprint-override"><code>str_to_convert = &quot;foo.bar&quot;\nexec(f&quot;x = {str_to_convert}&quot;)\nx()\n</code></pre>\n<p>as for your question, you only need to add your module name <code>foo</code> and <code>.</code> before <code>{}</code> as follows:</p>\n<pre class="lang-py prettyprint-override"><code>str_to_convert = &quot;bar&quot;\nexec(f&quot;x = foo.{str_to_convert}&quot;)\nx()\n</code></pre>\n<p><strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong>\n<strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong>\n<strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong></p>\n'}, {'answer_id': 68283436, 'author': 'Aliakbar Ahmadi', 'author_id': 4879852, 'author_profile': 'https://Stackoverflow.com/users/4879852', 'pm_score': 4, 'selected': False, 'text': "<p>In python3, you can use the <code>__getattribute__</code> method. See following example with a list method name string:</p>\n<pre><code>func_name = 'reverse'\n\nl = [1, 2, 3, 4]\nprint(l)\n&gt;&gt; [1, 2, 3, 4]\n\nl.__getattribute__(func_name)()\nprint(l)\n&gt;&gt; [4, 3, 2, 1]\n</code></pre>\n"}, {'answer_id': 69249811, 'author': 'U12-Forward', 'author_id': 8708364, 'author_profile': 'https://Stackoverflow.com/users/8708364', 'pm_score': 3, 'selected': False, 'text': "<p>Nobody mentioned <code>operator.attrgetter</code> yet:</p>\n<pre><code>&gt;&gt;&gt; from operator import attrgetter\n&gt;&gt;&gt; l = [1, 2, 3]\n&gt;&gt;&gt; attrgetter('reverse')(l)()\n&gt;&gt;&gt; l\n[3, 2, 1]\n&gt;&gt;&gt; \n</code></pre>\n"}, {'answer_id': 70526558, 'author': 'Franz Kurt', 'author_id': 7327114, 'author_profile': 'https://Stackoverflow.com/users/7327114', 'pm_score': -1, 'selected': False, 'text': '<p>You means get the pointer to an inner function from a module</p>\n<pre><code>import foo\nmethod = foo.bar\nexecuted = method(parameter)\n</code></pre>\n<p>This is not a better pythonic way indeed is possible for punctual cases</p>\n'}]
['https://Stackoverflow.com/questions/3061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121/']