Home  >  Article  >  Backend Development  >  How does Python's import work?

How does Python's import work?

王林
王林forward
2023-05-15 20:13:041646browse

Hello, I am somenzz, you can call me Brother Zheng.

Python’s import is very intuitive, but even so, sometimes you will find that even though the package is there, we will still encounter ModuleNotFoundError. Even though the relative path is very correct, an error is reported

ImportError: attempted relative import with no known parent package

Importing modules in the same directory and modules in different directories are completely different. This article analyzes some problems often encountered when using import to help you easily handle import. Based on this, you can easily create your own package.

1. What is a module (module) and what is a package (package)

Module (module)

The relationship between modules and packages can be compared to files and directories. Modules Just files.

As described in the Python documentation, a Python file is a module, and the Python file name (without the suffix .py) is the module name.

A module can contain variables, functions and classes, which are part of the namespace defined by the module, so the naming of variables is not a problem because two different modules can have variables, functions and classes with the same name. .

Package

The relationship between modules and packages can be compared to files and directories. A package is a directory.

Package can have modules or sub-packages. A module defines a namespace so that variables, functions and classes can have the same name in two different modules. Similarly, a package does the same for its component packages and modules. The main package can be accessed through the dot. modules and packages in .

A basic package can include sub-package, modules, __init__.py (not required after Python 3.3), setup.py. A possible package structure looks like this:

Python 的 import 是怎么工作的?

And setup.py exists in the home directory where your package is located, containing configuration information such as required dependencies, Scripts and subpackages. You can also specify metadata about the package, such as the package's name, author, description, etc.

setup.py is the file pip uses to install your package.

2.What happened during import

Let’s take a simple example first. For example, there are two files in the same directory, file1.py and file2.py. The content is very simple, just print The difference between their respective file names is that file1 is imported in file2.py:

#file1.py
print("This is file1.py")
#file2.py
print("This is file2.py")
import file1

When you run file2.py, you can get the following results:

❯ python file2.py
This is file2.py
This is file1.py

You can see:

  • import is very intuitive, whoever uses it can import it.
  • The import statement is an ordinary statement and can be placed anywhere.
  • When a file is imported, it will be executed, and its internal classes or objects will be added to its namespace.

We also need to know the search order of import. We only need to remember one thing, that is, import will search in sys.path.

For example, if I add a line of code at the end of file2.py: import sys; print(sys.path), I can print the import search path:

Python 的 import 是怎么工作的?

You can see the order of sys.path:

  • The path where the execution script is located will be searched first
  • Standard library
  • Third-party library site-packages

What you need to pay attention to about sys.path is:

  • In the interpreter environment, sys.path[0] is the path where the interpreter is started''
  • sys.path does not depend on the working path of the current program - os.getcwd(), but only depends on the path of the first script:

Python 的 import 是怎么工作的?

  • If one module imports another module, which in turn imports another module, the sys.path of the first module is where the interpreter searches for the second import statement.

Once a module or package is found, it will be executed. If there is an initialization file __init__.py in the package, __init__.py will be executed first when importing.

Then the project to be imported is added to its namespace, and we can use it through xx.yy.

3. When to use relative import and when to use absolute import

Let’s first look at what absolute import is. The so-called absolute import is in the form:

import aa
import aa.bb
from aa import bb

like this The method is very intuitive. Import will search in sys.path. If you encounter a ModuleNotFoundError, think about why sys.path does not have the package we want to import, or manually insert the path of the package into sys.path.

Let’s take a look at what relative import is. The so-called relative import is in the form:

from . import aa
from .aa import bb
from .. import yy

That is to say, there is a . sign in the relative path to indicate the module to be imported or the current module. The relative position of the package.

For example, we create a new directory subpackage1 under the pythonimportexample directory, and create two new files file3.py and file4.py in subpackage1.

The content is as follows:

file3.py :

print("This is file3.py")

file4.py:

from . import file3
print("This is file4.py")

只要我们直接运行 file4.py,那是一定会报错的:Python 的 import 是怎么工作的?

Python 提示我们:

ImportError: attempted relative import with no known parent package

也就是说相对导入不知道父包是谁,换句话说,这是一个子包,必须让父包来调用它,直接运行这个文件是不行的,即使你在 file4.py 的目录 subpackage1 同级的目录执行该文件也是不行的,见上图。

但是在 file4.py 的目录 subpackage1 同级的目录作为一个 module 来执行是可以的,如下图:

Python 的 import 是怎么工作的?

换句话说,我们把 subpackage1 作为一个包来让别人用,相对导入是可以的,比如说我们在目录 subpackage1 同级的目录新建一个 file5.py 的文件,内容如下:

file5.py:

from subpackage1 import file4。

然后,执行 python file5.py 可以看出,相对导入已经正常工作:

Python 的 import 是怎么工作的?

结论

  • 如果是当做脚本文件直接运行的,使用绝对导入。
  • 如果是当做模块供其他文件导入,使用相对导入。

4.一个自定义包的例子

先上一个图来看下目录及引用结构,方块的是目录,椭圆的是文件,曲线是引用:

Python 的 import 是怎么工作的?

其中 import_example 目录下有 setup.py 和 run.py

run.py 导入了 file4、file5、file6。

file4 导入了 file3,file5 导入了 file3。

file6 导入了 file2,file2 导入了 file1。

现在我们来执行一下 run.py 看下效果:

Python 的 import 是怎么工作的?

可以看出所有相对导入都已正常工作,虽然 file3 被导入了两次,但只执行了一次,说明 Python 内部已经考虑了同一个包的多重导入问题。

自定义包就是让其他文件导入使用的,因此 pythonimportexample目录下都使用相对导入,源代码见:

https://gitee.com/somenzz/code-example/tree/master/import_example

点阅读原文也可以直接访问。

这里还有一些自定义包的例子:

  • dbinterface[1]
  • transferfile[2]

最后的话

本文分享了什么是模块(module),什么是包(package),import 的搜索路径,也分享了相对导入和绝对导入的区别,最后举了一个非常实用的 import 例子,方便你构建自己的包。

The above is the detailed content of How does Python's import work?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete