Last Updated : 11 Jul, 2025
__import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those modules in runtime, we use __import__() function.
Let's understand with an example.
Python
s = "math"
m = __import__(s)
print(m.sqrt(16)) # Output: 4.0
Explanation:
__import__(name, globals, locals, fromlist, level)
Parameters:
locals()
)Return Type: returns a reference to the imported module object.
Examples of __import__():
Example 1:In this example, we will use the __import__() function to import the Python NumPy module dynamically to create an array.
Python
np = __import__('numpy')
# array from numpy
a = np.array([1, 2, 3])
print(type(a))
<class 'numpy.ndarray'>
Explanation:
Now, instead of trying to import the whole module, let's import only some specific functions from a module suing fromlist parameter.
Python
m = __import__('math', globals(), locals(), fromlist=['factorial'])
print(m.factorial(5))
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4