Home  >  Article  >  Backend Development  >  Comparison of the differences between import and __import__() in Python

Comparison of the differences between import and __import__() in Python

不言
不言Original
2018-09-20 16:09:462993browse

This article brings you a comparison of the differences between import and __import__() in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First let’s talk about the difference between the two:

The import instruction does two things: 1) Search for module, 2) Bind to local variables
Built-in function_ _import__() only does one thing: search for module

During the execution of the import instruction, __import__() is called to complete the Module retrieval.

The process of searching for modules:

Before understanding the search process, let’s first understand several roles in the internal implementation:
a) The module that has been searched will exist in a In the module cache (sys.modules).
b) finders | importers: Used to search for where the module is. After finding it, the module-spec is returned (including information such as where the module is, which loader should be used to load it, etc.).
The finders are found from the build-in module, and the importers are found from other locations.
Importers are extensible and can support certain paths, zips, and urls in the file system.
c) loaders: Load according to the modulespec to generate the module in python

module = modulespec.loader.load_module(modulespec.name)

The search process is as follows:

1) If the name of the module to be searched is in the cache (sys.modules) , then perform the following operations:
1.1) If the value is None, throw ModuleNotFoundError
1.2) The value is not None, directly return the value
2) Use finders to search from the built-in module, if it is not found by the importer When looking for it, the importers cannot be found. The name of the module is cached, the value is None, and then ModuleNotFoundError is raised.
When using importers to search, if you find .pyc, you need to first check whether .pyc is the latest.
After finding it, return to generate and create a module-spec
3) The loader in the module-spec loads and executes the module:

module = modulespec.loader.load_module(modulespec.name)
sys.modules[modulespec.name] = module
modulespec.loader.exec_module(module)

4) In the end, if it is not found, record the module name to the cache, the value is None, and then raise ModuleNotFoundError

The above is the detailed content of Comparison of the differences between import and __import__() 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