Follow

Follow
How to import modules from string in Python?

How to import modules from string in Python?

Dynamic module importing made easy with Python's importlib

Gaurav Sharma's photo
Gaurav Sharma
·Dec 27, 2022·

2 min read

Play this article

In Python, you can use the import statement to import a module or package into your code. However, sometimes you may want to dynamically import a module or package from a string, rather than hard coding the module or package name. In this article, we'll explore how to import modules from string in Python using the importlib module.

The importlib module provides a number of functions for interacting with the import system, including the import_module function, which can be used to import a module from a string. To use the import_module function, you need to pass it the name of the module as a string, and it will return the module object.

For example, to import the math module from a string, you can use the following code:

import importlib

module_name = 'math'
module = importlib.import_module(module_name)

Once you have the module object, you can use it like any other module, accessing its attributes and functions using the dot notation. For example, to use the pi constant from the math module, you can use the following code:

import importlib

module_name = 'math'
module = importlib.import_module(module_name)

print(module.pi)  # 3.141592653589793

You can also use the import_module function to import submodules or subpackages from a string. To do this, you simply need to include the submodule or subpackage name in the string, separated by a dot. For example, to import the urllib.parse module from a string, you can use the following code:

import importlib

module_name = 'urllib.parse'
module = importlib.import_module(module_name)

In addition to the import_module function, the importlib module also provides the import_from_string function, which allows you to import a module or object from a string containing the fully qualified name of the module or object. For example, to import the Decimal class from the decimal module from a string, you can use the following code:

import importlib

module_name = 'decimal.Decimal'
module = importlib.import_from_string(module_name)

decimal = module('3.14')
print(decimal)  # 3.14

In conclusion, the importlib module provides a number of functions for importing modules and objects from string in Python. By using these functions, you can dynamically import modules or objects

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this