Categories
Python Answers

How to call a function of a module by using its name string with Python?

Spread the love

Sometimes, we want to call a function of a module by using its name string with Python.

In this article, we’ll look at how to call a function of a module by using its name string with Python.

How to call a function of a module by using its name string with Python?

To call a function of a module by using its name string with Python, we can use the getattr function.

For instance, we write:

foo.py

def bar():
  print('bar')

Then we write:

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

We import the foo module with import foo.

Then we call getattr with the module and the name of the function we want to retrieve.

We assign the returned function to method_to_call.

Finally, we call method_to_call.

Therefore, we see 'bar' printed.

Conclusion

To call a function of a module by using its name string with Python, we can use the getattr function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *