Home > Article > Backend Development > How does Python's import work?
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.
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. .
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:
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.
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:
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:
You can see the order of sys.path:
What you need to pay attention to about sys.path is:
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.
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 提示我们:
ImportError: attempted relative import with no known parent package
也就是说相对导入不知道父包是谁,换句话说,这是一个子包,必须让父包来调用它,直接运行这个文件是不行的,即使你在 file4.py 的目录 subpackage1 同级的目录执行该文件也是不行的,见上图。
但是在 file4.py 的目录 subpackage1 同级的目录作为一个 module 来执行是可以的,如下图:
换句话说,我们把 subpackage1 作为一个包来让别人用,相对导入是可以的,比如说我们在目录 subpackage1 同级的目录新建一个 file5.py 的文件,内容如下:
file5.py:
from subpackage1 import file4。
然后,执行 python file5.py 可以看出,相对导入已经正常工作:
结论
先上一个图来看下目录及引用结构,方块的是目录,椭圆的是文件,曲线是引用:
其中 import_example 目录下有 setup.py 和 run.py
run.py 导入了 file4、file5、file6。
file4 导入了 file3,file5 导入了 file3。
file6 导入了 file2,file2 导入了 file1。
现在我们来执行一下 run.py 看下效果:
可以看出所有相对导入都已正常工作,虽然 file3 被导入了两次,但只执行了一次,说明 Python 内部已经考虑了同一个包的多重导入问题。
自定义包就是让其他文件导入使用的,因此 pythonimportexample目录下都使用相对导入,源代码见:
https://gitee.com/somenzz/code-example/tree/master/import_example
点阅读原文也可以直接访问。
这里还有一些自定义包的例子:
本文分享了什么是模块(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!