Search code examples
python-3.xgetattr

How to dynamically call class.function(value) in python 3


OK, so I have a string, x = module.class.test_function(value), and I want to call it and get the response. I've tried to use getattr(module.class, test_function)(value) yet it gives the error:

AttributeError: module 'module' has no attribute 'test_function'

I'm new to these things in python, how would I do this?


Solution

  • Given a file my_module.py:

    def my_func(greeting):
        print(f'{greeting} from my_func!')
    

    You can import your function and call it normally like this:

    >>> from my_module import my_func
    >>> my_func('hello')
    hello from my_func!
    

    Alternatively, if you want to import the function dynamically with getattr:

    >>> import my_module
    >>> getattr(my_module, 'my_func')
    <function my_func at 0x1086aa8c8>
    >>> a_func = getattr(my_module, 'my_func')
    >>> a_func('bonjour')
    bonjour from my_func!
    

    I would only recommend this style if it's required by your use case, for instance, the method name to be called not being known until runtime, methods being generated dynamically, or something like that.

    A good answer that explains getattr in more detail is - Why use setattr() and getattr() built-ins? and you can find a bit more at http://effbot.org/zone/python-getattr.htm.