Dynamic Import in Python

How to make you code more pluggable

Posted by Afsal on 24-Jun-2022

Hi Pythonistas!

Today we are going to learn about dynamic import in Python and where we can use this feature.

Dynamic import is importing a module based on a string. We are using importlib module for this.

Let's consider the example. We have 2 modules hello.py and hi.py both have a greeting function. We have to call the greeting method of hello or hi based on the user input. We have the first method import both module and call according to user input ie

Without dynamic import


def greeting(name):
    print(f"Hello {name}")


def greeting(name):
    print(f"Hi {name}")


import hello
import hi

module_name_selected = input("Enter the module (hello/hi): ")

if module_name_selected == "hello":

With dynamic import

import importlib
module_name_selected = input("Enter the module (hello/hi):")
module = importlib.import_module(module_name_selected)

Here in this second example, we use importlib.import_module this will import the module to our function. So using this we can reduce the unwanted import and if ladder. Also in the future, if an extra module is added we do not need to rewrite this code but without dynamic import, we need to update the code every time a new module is added. Also, this makes code more pluggable.

Hope you have learned a new concept from this post. Please share your valuable feedback at afsal@parseltongue.co.in