1989

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 foo, and I have a string whose content is "bar". What is the best way to call foo.bar()?

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

Tommy Herbert
  • 18,568
  • 14
  • 43
  • 56
ricree
  • 30,749
  • 13
  • 33
  • 27

14 Answers14

2381

Assuming module foo with method bar:

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

You could shorten lines 2 and 3 to:

result = getattr(foo, 'bar')()

if that makes more sense for your use case.

You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

Boris
  • 7,044
  • 6
  • 62
  • 63
Patrick Johnmeyer
  • 26,492
  • 2
  • 22
  • 24
  • 13
    hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python – Shaun Jun 03 '14 at 13:20
  • 12
    This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work. – Blairg23 Jun 21 '14 at 07:39
  • 9
    If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible. – geekofalltrades Aug 16 '14 at 18:01
  • 4
    See also the answer provided by @sastanin if you only care for example about your local/current module's functions. – NuSkooler Jun 19 '15 at 22:19
  • 2
    This does not work with functions that use a decorator. getattr returns the outer function – azmeuk Aug 26 '15 at 23:20
  • 2
    Note: cool +1, this made me understand once more that in Python everything is an object. Consequently, it works also with variables, you can access a module's variables as any other object's variables. – tuned Aug 29 '15 at 17:54
  • 1
    If you have deep structures, the following syntax might be useful: from functools import reduce reduce(getattr, "a.b.c.d.e.f.g".split('.'), deepStructure) – Robert Parcus Nov 05 '15 at 12:38
  • 1
    This is a very helpful answer, buy I couldn't work it out when the module foo is the current module itself. Does anybody know how to do that? – akki Sep 17 '16 at 06:07
  • 11
    @akki Yes, if you're *in* the `foo` module you can use `globals()` to do this: `methodToCall = globals()['bar']` – Ben Hoyt Dec 20 '16 at 19:06
  • 1
    You CAN do this, but SHOULD you? How will you find all instances of your function call when your code base gets large? There's nothing to grep for, and no IDE is going to find that reference. That makes this sort of dynamic call really troublesome. Isn't it nicer to your colleagues to be explicit, anyway? Less code doesn't doesn't always mean more readable. – KeatsKelleher Oct 23 '17 at 01:12
  • 2
    @KeatsKelleher since we do not know the use case, only the question, all I can say reliably is that there are many use cases in which your point applies, and some which they do not. It is common and reasonable to do things like this in rules engines, DSLs, in-app scripting, etc., in which the code you are writing exists to run other code. There are probably numerous other "good" times to do this that I'm not thinking of right now. So, _should_ we do this? The answer, as with most language features in most languages, is "it depends." – Patrick Johnmeyer Nov 13 '17 at 16:17
  • 2
    @PatrickJohnmeyer I never exclude patterns/paradigms entirely... This is why I asked a question instead of making a blanket statement. There are a lot of negative repercussions for using this pattern overzealously... which (at least in my experience) is common. – KeatsKelleher Nov 13 '17 at 16:21
  • 1
    In case, if the module itself is a string and one has to convert from str to class in this case "foo" is a string but it has to be called, then checkout this link https://blender.stackexchange.com/questions/36781/calling-a-method-from-a-string PS: I know it's doesn't belong in the context of the asked question, I thought someone might benefit from this comment. – Momooo Dec 12 '19 at 19:28
  • can we get this foo also from string? – conol Jan 24 '21 at 21:47
  • @conol you can, using something like `m = __import__('foo')`, where `m` is now the name used for module "foo". You would then do `method_to_call = getattr(m, 'bar')`. Calling `__import__` directly is rarely the right answer, but it is possible. https://stackoverflow.com/a/4605/363 – Patrick Johnmeyer Feb 06 '21 at 23:11
618
locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

sastanin
  • 36,792
  • 11
  • 94
  • 126
  • 69
    This method with globals/locals is good if the method you need to call is defined in the same module you are calling from. – Joelmob Oct 09 '14 at 21:36
  • @Joelmob is there any other way to get an object by string out of the root namespace? – Nick T Jan 26 '15 at 20:51
  • @NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more. – Joelmob Jan 27 '15 at 12:34
  • 1
    I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None. – David Stein Jan 30 '17 at 15:18
376

Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:

module = __import__('foo')
func = getattr(module, 'bar')
func()
Ben Hoyt
  • 9,208
  • 4
  • 52
  • 82
HS.
  • 14,004
  • 8
  • 36
  • 46
  • 98
    I do not understand that last comment. \_\_import\_\_ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer. – hoffmaje May 05 '12 at 09:33
  • 55
    Use `importlib.import_module`. The official docs say about `__import__`: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." http://docs.python.org/2/library/functions.html#__import__ – glarrain Aug 05 '13 at 22:07
  • 9
    @glarrain As long as you're ok with only support 2.7 and up. – Xiong Chiamiov Sep 14 '13 at 16:54
  • 2
    @Xiong Chaimiov, `importlib.import_module` is supported in 3.6 . See https://docs.python.org/3.6/library/importlib.html#importlib.import_module – cowlinator Oct 05 '17 at 19:28
  • 8
    @cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays. – Xiong Chiamiov Oct 05 '17 at 23:55
129

Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:

# Get class from globals and create an instance
m = globals()['our_class']()

# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')

# Call it
func()

For example:

class A:
    def __init__(self):
        pass

    def sampleFunc(self, arg):
        print('you called sampleFunc({})'.format(arg))

m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')

# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')

And, if not a class:

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

globals()['sampleFunc']('sample arg')
tbc0
  • 1,269
  • 14
  • 19
Sourcegeek
  • 1,299
  • 1
  • 8
  • 2
121

Given a string, with a complete python path to a function, this is how I went about getting the result of said function:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()
ferrouswheel
  • 3,060
  • 1
  • 21
  • 24
66

The best answer according to the Python programming FAQ would be:

functions = {'myfoo': foo.bar}

mystring = 'myfoo'
if mystring in functions:
    functions[mystring]()

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

53

The answer (I hope) no one ever wanted

Eval like behavior

getattr(locals().get("foo") or globals().get("foo"), "bar")()

Why not add auto-importing

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

In case we have extra dictionaries we want to check

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

We need to go deeper

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()
00500005
  • 2,988
  • 2
  • 27
  • 37
29

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:

myFnName  = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn  = getattr(app,myFnName)
trubliphone
  • 3,115
  • 2
  • 32
  • 49
25

Try this. While this still uses eval, it only uses it to summon the function from the current context. Then, you have the real function to use as you wish.

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 only the function-related errors when you call.

def say_hello(name):
    print 'Hello {}!'.format(name)

# get the function by name
method_name = 'say_hello'
method = eval(method_name)

# call it like a regular function later
args = ['friend']
kwargs = {}
method(*args, **kwargs)
tvt173
  • 1,368
  • 17
  • 16
  • 2
    This would be risky. string can have anything and eval would end up eval-ling it without any consideration. – iankit Dec 30 '16 at 18:13
  • 5
    Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks. – tvt173 Jan 06 '17 at 18:48
  • 3
    A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky. – red777 Aug 14 '18 at 11:01
  • 2
    You should never use `eval` unless strictly necessary. `getattr(__module__, method_name)` is a much better choice in this context. – moi Jan 14 '19 at 12:05
13

none of what was suggested helped me. I did discover this though.

<object>.__getattribute__(<string name>)(<params>)

I am using python 2.66

Hope this helps

Natdrip
  • 866
  • 1
  • 9
  • 22
  • 20
    In what aspect is this better than getattr() ? – V13 Jul 29 '16 at 12:26
  • 1
    Exactly what i wanted. Works like a charm! Perfect!! `self.__getattribute__('title')` is equal to `self.title` – ioaniatr Aug 06 '18 at 18:49
  • `self.__getattribute__('title')` doesn't work in any cases(don't know why) afterall, but `func = getattr(self, 'title'); func();` does. So, maybe is better to use `getattr()` instead – ioaniatr Aug 16 '18 at 16:52
  • 15
    Can people who don't know python please stop upvoting this junk? Use [`getattr`](https://docs.python.org/3/library/functions.html#getattr) instead. – Aran-Fey Oct 23 '18 at 05:19
9

As this question How to dynamically call methods within a class using method-name assignment to a variable [duplicate] marked as a duplicate as this one, I am posting a related answer here:

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:

class MyClass:
    def __init__(self, i):
        self.i = i

    def get(self):
        func = getattr(MyClass, 'function{}'.format(self.i))
        func(self, 12)   # This one will work
        # self.func(12)    # But this does NOT work.


    def function1(self, p1):
        print('function1: {}'.format(p1))
        # do other stuff

    def function2(self, p1):
        print('function2: {}'.format(p1))
        # do other stuff


if __name__ == "__main__":
    class1 = MyClass(1)
    class1.get()
    class2 = MyClass(2)
    class2.get()

Output (Python 3.7.x)

function1: 12

function2: 12

Serjik
  • 9,013
  • 6
  • 57
  • 65
6

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 x = eval('foo.bar')(). And when you implement some error handling then quite securely (the same principle can be used for getattr). Example with module import and class:

# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)

# also class method returning (or not) value(s) can be used with eval: 
class Say:
    def say(something='nothing'):
        return something

bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you' 

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:

# try/except block can be used to catch both errors
try:
    eval('Say.talk')() # raises AttributeError because function does not exist
    eval('Says.say')() # raises NameError because the class does not exist
    # or the same with getattr:
    getattr(Say, 'talk')() # raises AttributeError
    getattr(Says, 'say')() # raises NameError
except AttributeError:
    # do domething or just...
    print('Function does not exist')
except NameError:
    # do domething or just...
    print('Module does not exist')
Lukas
  • 1,027
  • 10
  • 14
3

getattr calls method by name from an object. But this object should be parent of calling class. The parent class can be got by super(self.__class__, self)

class Base:
    def call_base(func):
        """This does not work"""
        def new_func(self, *args, **kwargs):
            name = func.__name__
            getattr(super(self.__class__, self), name)(*args, **kwargs)
        return new_func

    def f(self, *args):
        print(f"BASE method invoked.")

    def g(self, *args):
        print(f"BASE method invoked.")

class Inherit(Base):
    @Base.call_base
    def f(self, *args):
        """function body will be ignored by the decorator."""
        pass

    @Base.call_base
    def g(self, *args):
        """function body will be ignored by the decorator."""
        pass

Inherit().f() # The goal is to print "BASE method invoked."
정도유
  • 474
  • 3
  • 6
-11

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 clear to cls, Linux and Mac users leave as is for example) or just execute it, respectively.

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")
Number File
  • 183
  • 5