Home >Backend Development >Python Tutorial >How Do `__import__` and `importlib.import_module` Differ When Importing Modules from Strings in Python?

How Do `__import__` and `importlib.import_module` Differ When Importing Modules from Strings in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 09:08:15197browse

How Do `__import__` and `importlib.import_module` Differ When Importing Modules from Strings in Python?

Different Outcomes Using "__import__" and Import Statement for Importing Modules from Strings

When working with nested libraries, a common task is to dynamically import submodules using a string variable as the import path. However, the "__import__" function can yield different results compared to a typical import statement.

In your example, when using "__import__" without specifying the "fromlist" argument:

i = __import__('matplotlib.text')

the imported module i includes both the base matplotlib module and something additional. To specifically import the matplotlib.text submodule, you can modify the code to:

i = __import__('matplotlib.text', fromlist=[''])

In Python 3.1 or later, you can also use the importlib module:

import importlib

i = importlib.import_module("matplotlib.text")

Here are a few additional notes to consider:

  • For importing modules from sub-folders, the import path should be specified accordingly. For example, to import email.py from the feature sub-folder, use:
importlib.import_module("feature.email")
  • Before Python 3.3, it was mandatory to have an __init__.py file in the folder containing the module being imported. This is no longer required as of Python 3.3.

The above is the detailed content of How Do `__import__` and `importlib.import_module` Differ When Importing Modules from Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Some QtGui structuresNext article:Some QtGui structures