Import learning notes in python

Source: Internet
Author: User
The import statement in python is used to import modules. There are a large number of modules available in the python module library. to use these files, you must use the import statement to import the specified module to the current program. The following article describes the import learning materials in python. 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 have a file _ init __. in this way, the directory name is the module name, and the python file in the package can also use the package name. file name import

Import syntax

There are two import syntax types:

1. direct import Module

import Moduleimport Module as xx

2. import objects from the module (lower-level modules, classes, functions, variables, etc)

from Module import Namefrom 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 Aimport 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 whether there is A in sys. modules. If yes, it is not loaded. if not, create A module object for A and load

If it is from A import B, first create A module object for A, then parse A, find B, and fill in _ dict _ of

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 B. py. execute from A import AA in the first line, and then scan A. py again.

Scan. in the first line of py, execute from B import BB. because Step 1 has already created a module object for B, it will get BB directly from _ dict _ of module object of B, 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 the _ init _. py file, this 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.

During the import package, the sub-packages, files, and classes, functions, and variables in _ init _. py 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

Error ImportError: No module named xxx, because when we execute import A. B, both A and B must be modules (files or packages)

Relative import and absolute import

The absolute import format is import. B or from A import B. The relative import format is from. import B or from .. A import B ,. indicates the current module ,.. indicates the upper-layer module ,... indicates upper-layer modules, 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

The app/start. py content is import mod1.file1

The content of app/mod1/file1.py is from .. mod2 import file2

To facilitate analysis, we add print _ file __, _ name _ to the first line of all py files (including _ init _. py __

Currently, relative import is used in app/mod1/file1.py. if we run python file1.py in app/mod1 or python mod1/file1.py in app, the following error occurs: attempted relative import in non-package

ValueError: Attempted relative import beyond toplevel package will be reported when python-m mod1.file1 or python start. py is executed in the app.

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. here _ init _ is not listed for the purpose of simple display __. py file, when file. the package structure of py is. b1.C1. file. in the file. the following absolute import can be used in py:

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 python-m A. B1.C1. file in the upper-level directory of A. The package structure is explicitly specified.

Create the file start in the upper-level directory of. py, in start. py contains import. b1.C1. file, and then execute python start. in this case, the package structure is based on file. in the _ name _ variable of py

Let's look at the two previous errors. The first method is to execute python file1.py and python mod1/file1.py. in this case, file. the _ name _ of py is _ main _. In other words, it is a top-level module and has no package structure. Therefore, an error is reported.

In the second case, run python-m mod1.file1 and python start. in py, the former explicitly tells the interpreter that mod1 is the top-level module, while the latter needs to import file1, while the _ name _ of file1.py is mod1.file1, and the top-level module is also mod1, therefore, execute from .. in file1.py .. when mod2 is imported to file2, an error is reported because mod2 is not in the top-level module mod1. It can be seen from the error stack that the relative import error in file1.py is not returned when the start. py file is definitely imported.

There are two ways to execute python-m app in the app directory. mod1.file1, the other is to change the directory structure, 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

Change start. py to import pkg. mod1.file1, and then run python start. py in the app.

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.

For more articles related to import learning notes in python, please follow the PHP Chinese network!

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.