Python import learning notes, pythonimport

Source: Internet
Author: User

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__.pyIn 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

  1. If it is import A, checksys.modulesWhether A already exists. If yes, It is not loaded. If not, it creates A module object for A and loads
  2. 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:

  1. 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
  2. Scan the first line of B. py for executionfrom A import AAIn this case, A. py will be scanned again.
  3. Scan the first line of A. pyfrom B import BBBecause 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,

  1. Change from B import BB to import B, or change from A import AA to import.
  2. 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__.pyThe 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__.pyClasses, 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 xxxBecause 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.BOrfrom A import B, The relative import format isfrom . import BOrfrom ..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.pyContent isimport mod1.file1

app/mod1/file1.pyContent isfrom ..mod2 import file2

For ease of analysis, we__init__.py) Add the first lineprint __file__, __name__

Nowapp/mod1/file1.pyThe relative import is used in the app/mod1.python file1.pyOr run the command in the app.python mod1/file1.pyAn error is reported.ValueError: Attempted relative import in non-package

Run in apppython -m mod1.file1Orpython start.pyAn 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

  1. 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
  2. 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__.pyFile. When the Package Structure of file. py is A. B1.C1. file (note that__name__Instead of the disk directory structure, runfile.pyWhen the corresponding package directory structure is different ),file.pyThe 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:

  1. Run the command in the upper-level directory of.python -m A.B1.C1.fileThe package structure is explicitly specified.
  2. Create the file start. py in the upper-level directory of.start.pyImport A. B1.C1. file, and then executepython start.pyIn this case, the package structure is based onfile.pyOf__name__Variable

Let's look at the two previous errors. The first is execution.python file1.pyAndpython mod1/file1.py.file.pyOf__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.file1Andpython start.pyThe former explicitly tells the interpreter that mod1 is the top-level module, and the latter needs to import file1, whilefile1.pyOf__name__Ismod1.file1The top-level module is also mod1, so infile1.pyExecutedfrom ..mod2 import file2An error is reported because mod2 is not in the mod1 module of the top layer. The error stack shows thatstart.pyAn error is returned when the import is absolute.file1.pyError 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.file1The 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.pyChange contentimport pkg.mod1.file1And 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.

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.