Detailed description of relative and absolute import in Python

Source: Internet
Author: User
Absolute import means skipping the package and directly searching for sys. path, and searching for modules based on sys. path. The relative import refers to the first package, the second package, and the second package. the following article mainly introduces the relative import and absolute import in Python. if you need them, you can refer to them for reference, let's take a look. Preface

Python is relatively imported and absolutely imported. These two concepts are relative to package import. Package import is the module in the package import package.

Search path of Python import

Search for this module in the current directory

Search in the path list specified in the environment variable PYTHONPATH.

Search for the lib library in the Python installation path

Python import steps

All python loaded module information is stored in the sys. modules structure. when you import a module, it will follow the steps below

If it is import A, check whether there is A in sys. modules. If yes, it is not loaded. if not, create A module object for A and load

If it is from A import B, first create A module object for A, then parse A, find B, and fill in _ dict _ of

Relative import and absolute import

The absolute import format is import. B or from A import B. The relative import format is from. import B or from .. A import B ,. indicates the current module ,.. indicates the upper-layer module ,... indicates upper-layer modules, and so on.

Relative import can avoid maintenance problems caused by hard encoding. for example, if we change the name of a top-level package, all the imports of its sub-packages will not be available. However, modules with relative import statements cannot be run directly; otherwise, an exception occurs:

ValueError: Attempted relative import in non-package

Why? We need to first understand some rules for importing modules:

If the package structure is not explicitly specified, Python determines the structure of a module in the package based on _ name, if it is _ main _, it is A top-level module with no package structure. if it is. B .C structure, the top-level module is. Basically, this principle is followed:

For absolute import, a module can only import its own sub-modules or modules at the same level as its top-level modules and their sub-modules

For relative import, a module must have a package structure and can only import modules in its top-level module.

If a module is run directly, it is a top-level module and does not have a hierarchy. therefore, no other relative paths can be found.

Python2.x imports relative paths by default, and Python3.x imports absolute paths by default. Absolute import can avoid overwriting the standard library module by importing sub-packages (conflicts may occur due to the same name ). If you want to use absolute import by default in Python2.x, you can add the following statement at the beginning of the file:

from __future__ import absolute_import

From _ future _ import absolute_import

This import statement does not mean to regard all imports as absolute imports, but to disable implicit relative import (implicit relative import), but does not disable explicit relative import (display relative import ).

So what is implicit relative import and display relative import? Let's look at an example, assuming the following package structure:

thing├── books│ ├── adventure.py│ ├── history.py│ ├── horror.py│ ├── __init__.py│ └── lovestory.py├── furniture│ ├── armchair.py│ ├── bench.py│ ├── __init__.py│ ├── screen.py│ └── stool.py└── __init__.py

If the role is referenced in stool, the following methods are available:

Import plugin # This is implicit relative importfrom. import plugin # This is explicit relative importfrom furniture import plugin # This is absolute import

Implicit comparison means that it does not tell the interpreter relative to whom, but it is relative to the current module by default, while explicit comparison clearly tells the interpreter relative to who to import. The third method is officially recommended. The first method is highly recommended by the official team. Python3 has been deprecated. this method can only be used to import modules in the path.

Relatively and absolutely only for intra-package import

Finally, we emphasize that the relative import and absolute import are only for package import, otherwise the content discussed in this article will be meaningless. The so-called package contains _ init __. directory of the py file, which is first executed during package import. the file can be empty or add any legal Python code to it.

Compared with importing, hard encoding is avoided, and package maintenance is friendly. Absolute import can avoid conflicts with the standard library naming. In fact, we do not recommend that you use the same custom modules as standard library commands.

As mentioned above, modules with relative imports cannot be directly run. In fact, modules with absolute imports cannot be directly run. ImportError may occur:

ImportError: No module named XXX

This is the same reason as absolute import. To run A package containing absolute and relative import modules, you can use python-m A. B .C to tell the interpreter module hierarchy.

Someone may ask: if there are two modules a. py and B. py in the same directory, why can I import a in B. py?

This is because the directory where these two files are located is not a package, so each python file is an independent module that can be directly imported by other modules, just like importing a standard library, they do not have problems with relative and absolute import. Relative import and absolute import are only used inside the package.

Summary

The above is all about this article. I hope this article will help you learn or use python. if you have any questions, please leave a message.

For more details about the relative import and absolute import articles in Python, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.