0

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?

10
  • Can you show this as a running script? Is test_function supposed to be a variable with the function name in it? What is thing.class? Does print(thing.class) give a hint? Commented May 23, 2018 at 2:14
  • It looks like thing.class is a module so the question is, where did it come from? Commented May 23, 2018 at 2:14
  • Yes test_function is a variable with the function name in it Commented May 23, 2018 at 2:15
  • The error message says that module.class is in fact a module called "module" and it doesn't have a variable called "test_function". There really isn't much else we can say without more information. Commented May 23, 2018 at 2:21
  • But what is the syntax of calling class.function(value) when class and function and value are variables cointaining the class and function names and what to input to the function. Commented May 23, 2018 at 2:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.