While writing a code, there might be a need for some specific modules. So we import those modules by using a single line code in Python.
But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use the Python’s inbuilt
__import__() function. It helps to import modules in runtime also.
Syntax: __import__(name, globals, locals, fromlist, level)
name : Name of the module to be imported
globals and locals : Interpret names
formlist : Objects or submodules to be imported (as a list)
level : Specifies whether to use absolute or relative imports. Default is -1(absolute and relative).
Example #1 :
Example #2 :
Both the following statements has same meaning and does the same work.
__import__() is not really necessary in everyday Python programming. Its direct use is rare. But sometimes, when there is a need of importing modules during the runtime, this function comes quite handy.
- Import module in Python
- Why import star in Python is a bad idea
- Create and Import modules in Python
- How to import JSON File in MongoDB using Python?
- How to import an excel file into Python using Pandas?
- Different ways to import csv file in Pandas
- Ways to import CSV files in Google Colab
- How to import excel file and find a specific column using Pandas?
- Python - Call function from another function
- Wand function() function in Python
- Returning a function from a function - Python
- wxPython - GetField() function function in wx.StatusBar
- How to write an empty function in Python - pass statement?
- Function Decorators in Python | Set 1 (Introduction)
- Vulnerability in input() function – Python 2.x
- Function Annotations in Python
- Sorted() function in Python
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Python Numbers | choice() function
- Python | askopenfile() function in Tkinter
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.