SoFunction
Updated on 2025-03-01

Parse Import in Python3

Search path for Python import

The search path for import is:

  • Search for "built-in module"
  • Paths in Search
  • When initializing, the following paths will be added in order:

The directory where you are located (if it is a soft link, then it is the real directory where you are located) or the current directory;

Environment variables Directory listed in PYTHONPATH (similar to environment variable PATH, defined by the user, default to empty);
The path 1 added when the site module is imported (site will be automatically imported at runtime).

The path added to import site is generally XXX/site-packages. If you are too lazy to remember the initialization process, you can simply think that the search order of import is:

Built-in modules

The directory where the .py file resides
packages installed by pip or easy_install

Absolute and relative imports

The relationship between absolute import and relative import can be compared to absolute paths and relative paths.

The absolute import format is:

import 
or
from A import B

The relative import format is:

from . import B
or
from ..A import B

Among them, the dot number represents the current module,... represents the upper module,... represents the upper module, and so on.

How to execute the module

There are two ways to execute a module: direct execution and as a module, i.e.:

python example/
or
python -m 

Note that when executing as a module, there must be a concept of package, that is, example must be a package, and foo is the module under this package, so that it can be executed smoothly.

Packages and modules

Module: A .py file is a module

Package: The directory where the init .py file is the package (package)

Tests in various situations

Direct import of modules

That is, the directory where the module is located is not a package structure, and each module is independent, such as the following directory structure:

D:\LEARN\IMPORT_TEST\TEST1
├─pack1
│  
└─pack2
  


The contents in it are:

import sys
("D:\\learn\\import_test\\TEST1\\pack2")
from modu2 import hello2
hello2()


The contents in it are:

def hello2():
 print("hello, I am module 2")


Note that part of the content must be added to modu1, that is, according to the above description, you must make modu1 find modu2, otherwise the following error will occur:

ModuleNotFoundError: No module named 'modu2'

At this time, enter the pack1 directory and output smoothly by direct execution or module execution.

Out-of-sourcing import

Turn the directory where the above two modules are located into a package structure, that is:

D:\LEARN\IMPORT_TEST\TEST2
├─pack1
│  
│  __init__.py
└─pack2
  
  __init__.py


At this time, it can also be executed smoothly, and at the same time, there is one more execution method than the non-package structure above, namely:

python -m pack1.modu1

That is, it is executed in the form of package name + module name.

In the above two situations, the module and module, and the package are all independent of each other, so there is no relative import meaning.

If it is importing different modules in a package, then the most natural thing is to use relative import.

Relative import within the package

D:\LEARN\IMPORT_TEST\Test3
│ __init__.py
│
├─pack1
│  
│  __init__.py
│
└─pack2
  
  __init__.py


The content at this time is:

from ..pack2.modu2 import hello2
hello2()


It is about to be removed because it is referenced in a package, so it is meaningless to write like this at this time.

The correct way to run at this time is to enter the folder on the previous layer of Test3, and then:

python -m Test3.pack1.modu1

That is, it clearly tells the interpreter module's hierarchy.

If you use direct operation method, for example:

python Test3\pack1\

The following error will be reported:

ValueError: attempted relative import beyond top-level package

This is because the name of the module is imported (the name here and the main below are both underlined, but the web page cannot be displayed.) attributes determine the position of the module in the package structure. When the name attribute does not contain package information (. There is no hierarchy represented by '.', such as 'main'), relative import parses the module into a top-level module regardless of the actual location of the module in the file system. When the module is run directly, it itself is a top-level module, and there is no hierarchy, so no other relative path can be found.

Therefore, it is not possible to directly run a module with relative imports. You need to clearly tell the package structure through the module operation method.

This principle also applies to the following error, such as moving modu2 into pack1, that is, in the same directory as modu1, and then changing the content of modu1 to such a relative reference:

from .modu2 import hello2
hello2()

There is no problem using the module execution method at this time. If you still want to try to run it directly, then:

ModuleNotFoundError: No module named '__main__.modu2'; '__main__' is not a package

The reason is that there is no package structure at this time, and main is not a package either.

Then the solution is to either use the module to run it, or change it to the absolute import method below and run it directly.

Absolute import within the package

Then, if the content in it is changed to absolute import, that is:

from Test3.pack2.modu2 import hello2
hello2()

At this time, the correct way to run is to enter the folder on the previous layer of Test3, and then run it using the module execution method:

python -m Test3.pack1.modu1

If you use direct operation method at this time:

python Test3\pack1\

Then an error will be reported:

ModuleNotFoundError: No module named 'Test3'

This is mainly because Test3 is not found, that is, according to the first part, Test3 is not in the search path of import. So, just add it in, for example:

set PYTHONPATH=D:\learn\import_test\

There is no problem running directly at this time.

Summarize

The above is the Import understanding in Python 3 introduced to you by the editor. I hope it will be helpful to everyone!