In this Python tutorial, we will explore how to import a Python Module using a string representation of its name. We will achieve this task using the Python importlib module, which provides us with the required functionality.
It is important to note that this library is only available on Python 2.7, and Python 3.1 and above.
Import Python Module using importlib
Normally, when we want to import modules/libraries in Python, we follow the below format.
However, we may wish to import libraries during run-time, or based on user input. This may lead us to trying the following approach(es).
import "matplotlib" # Wrong str = "matplotlib" import str # Wrong
Both of the above approaches are wrong, and will not work as intended. This is where the Python importlib library comes in.
We will be using the importlib library’s
import_module() function. This function takes as parameter, a string that represents the library you wish to import.
Let’s take a look at how to import a module using this function.
import importlib lib = importlib.import_module("random") for i in range(5): print(lib.randint(1, 10))
7 1 1 4 10
Once you have called
import_module() function, it will return a library object. Every time you want to use a function from the imported library, you must do it through the library object.
In the above example, we imported the random library, used to generate random numbers. It has a variety of different functions, one of which is
randint(). Normally we might do
random.randint() to call this, but when using importlib, we need to do
lib is an arbitrary name)
More about importlib
Some special cases can arise, such as when you need to import a sub-module. The below code shows how you would go about doing so.
import importlib lib = importlib.import_module("matplotlib.pyplot") lib.plot([1, 2, 3, 4], [1, 4, 9, 16]) lib.show()
Normally, this would have been the following statement.
For more information about importlib, please refer to the dedicated section for the Python importlib module.
This marks the end of the “Import Python Module from String” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section.