Languages
[Edit]
EN

Python - call function of a module by using its name as a string

0 points
Created by:
MMORex
510

In this article, we would like to show you how to call a function of a module by using its name as a string in Python.

Quick solution:

import math

method = getattr(math, "sqrt")
print(method(16))  # 4.0

 

Practical example

In this example, we use getattr() method to get the sqrt method from math module.

import math

method = getattr(math, "sqrt")
result = method(16)

print(result)   # 4.0

Output:

4.0
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - string (popular problems)

Python - call function of a module by using its name as a string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join