Python import learning notes, pythonimport
Preface
There are two ways to organize python modules. One is a simple python file, the file name is the module name, the other is a package, and the package is a directory containing several python files, the directory must contain a file.__init__.py
In this way, the directory name is the module name, And the python file in the package can also be imported using the package name. File Name method.
Import syntax
There are two import syntax types:
1. Direct import module
import Module import Module as xx
2. import objects from the module (lower-level modules, classes, functions, variables, etc)
from Module import Name from Module immport Name as yy
The as syntax is used to set the alias of an object (here, the object refers to a module, class, function, and so on). The import introduces the object name to the namespace of the current file.
Assume that the following directory structure is available:
├── A.py└── pkg ├── B.py └── __init__.py
The following statements are valid in the current directory.
import A import pkgimport pkg.Bfrom pkg import B
To simplify the discussion, the as syntax will not be used as an example below
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
sys.modules
Whether A already exists. If yes, It is not loaded. If not, it creates A module object for A and loads
- If it is from A import B, first create A module object for A, then parse A, find B, and fill in
__dict__
Medium
Nested import
In the import module, we may worry about whether A module will be imported multiple times. Assume that there are three modules A, B, and C. A needs to import B, C, and B to import C again, in this way, A will execute two import C statements, one is its own import statement, and the other is the import Statement executed at import B. However, according to the import steps described above, during the second import, we found that the module has been loaded, so we will not repeat the import
However, an error is reported in the following cases:
#filename: A.pyfrom B import BBclass AA:pass#filename: B.pyfrom A import AAclass BB:pass
At this time, whether A. py or B. py is executed, an ImportError exception will be thrown. Suppose we are executing A. py. The reason is as follows:
- In File A. py, execute from B import BB and scan B. py first. At the same time, create A module object for B in the namespace of A, and try to find BB from B
- Scan the first line of B. py for execution
from A import AA
In this case, A. py will be scanned again.
- Scan the first line of A. py
from B import BB
Because step 1 has created a module object for module B__dict__
Obtain BB in. Obviously, BB cannot be obtained, so an exception is thrown.
There are two solutions to this situation,
- Change from B import BB to import B, or change from A import AA to import.
- Place the two lines of code in A. py or B. py
In short, it should be noted that the import should be performed whenever necessary.
Package import
When a directory contains__init__.py
The directory is a python package.
The import package is the same as the import single file. We can use the following analogy:
- When you import a single file, all the classes, functions, and variables in the file can be used as import objects.
- The sub-packages, files, and
__init__.py
Classes, functions, and variables can all be used as import objects.
Assume that the following directory structure is available:
pkg├── __init__.py└── file.py
The content of _ init _. py is as follows:
argument = 0class A:pass
Execute the following statement in the directory at the same level as pkg: OK
>>> import pkg>>> import pkg.file>>> from pkg import file>>> from pkg import A>>> from pkg import argument
The following statement is incorrect.
>>> import pkg.A>>> import pkg.argument
ErrorImportError: No module named xxx
Because when we executeimport A.B
, Both A and B must be modules (files or packages)
Relative import and absolute Import
The absolute import format isimport A.B
Orfrom A import B
, The relative import format isfrom . import B
Orfrom ..A import B
,. Indicates the current module,... indicates the upper-layer module,... indicates the upper-layer module, and so on. When we have multiple packages, we may need to import the content of another package from one package. This will produce absolute import, which is often the most prone to errors, or use specific examples to describe
The directory structure is as follows:
app├── __inti__.py├── mod1│ ├── file1.py│ └── __init__.py├── mod2│ ├── file2.py│ └── __init__.py└── start.py
Whereapp/start.py
Content isimport mod1.file1
app/mod1/file1.py
Content isfrom ..mod2 import file2
For ease of analysis, we__init__.py
) Add the first lineprint __file__, __name__
Nowapp/mod1/file1.py
The relative import is used in the app/mod1.python file1.py
Or run the command in the app.python mod1/file1.py
An error is reported.ValueError: Attempted relative import in non-package
Run in apppython -m mod1.file1
Orpython start.py
An error is reported.ValueError: Attempted relative import beyond toplevel package
Next, let's take a look at 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 follow this principle
- 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.
The directory structure is as follows:
A├── B1│ ├── C1│ │ └── file.py│ └── C2└── B2
A, B1, B2, C1, and C2 are all packages.__init__.py
File. When the Package Structure of file. py is A. B1.C1. file (note that__name__
Instead of the disk directory structure, runfile.py
When the corresponding package directory structure is different ),file.py
The following absolute import can be used:
import A.B1.C2import A.B2
And the following relative import
from .. import C2from ... import B2
Under what circumstances will the Package Structure of file. py be a. B1.C1. file? There are two types:
- Run the command in the upper-level directory of.
python -m A.B1.C1.file
The package structure is explicitly specified.
- Create the file start. py in the upper-level directory of.
start.py
Import A. B1.C1. file, and then executepython start.py
In this case, the package structure is based onfile.py
Of__name__
Variable
Let's look at the two previous errors. The first is execution.python file1.py
Andpython mod1/file1.py
.file.py
Of__name__
Is__main__
In other words, it is a top-level module and has no package structure. Therefore, an error is reported.
In the second casepython -m mod1.file1
Andpython start.py
The former explicitly tells the interpreter that mod1 is the top-level module, and the latter needs to import file1, whilefile1.py
Of__name__
Ismod1.file1
The top-level module is also mod1, so infile1.py
Executedfrom ..mod2 import file2
An error is reported because mod2 is not in the mod1 module of the top layer. The error stack shows thatstart.py
An error is returned when the import is absolute.file1.py
Error reported during relative import
In this case, how can we perform these operations in a directory on the upper layer of the app?python -m app.mod1.file1
The other is to change the directory structure and put all the packages in a large package, as shown below:
app├── pkg│ ├── __init__.py│ ├── mod1│ │ ├── __init__.py│ │ └── file1.py│ └── mod2│ ├── __init__.py│ └── file2.py└── start.py
start.py
Change contentimport pkg.mod1.file1
And then runpython start.py
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.