Python in Import Learn memo notes

Source: Internet
Author: User
Objective

In the Python module has two kinds of organization, one is a simple Python file, the file name is the module name, one is a package, the package is a directory containing a number of Python files, directory must have a file __init__.py, so the directory name is the module name, The python file in the package can also be used by the package name. File Name Import

Import syntax

Import syntax is available in two ways

1. Direct Import Module

Import Moduleimport Module as XX

2. Import objects from modules (sub-modules, classes, functions, variables, etc.)

From Module import Namefrom Module immport Name as yy

As syntax is used to set the object (which is used to refer to modules, classes, functions, etc.) aliases, import the object name into the current file namespace

Suppose you have the following directory structure

├──a.py└──pkg├──b.py└──__init__.py

In the current directory, the following statements are valid

Import Aimport pkgimport pkg. Bfrom pkg Import B

To simplify the discussion, an example of the as syntax will not be shown below

Import Step

Python all loaded module information is stored in the sys.modules structure, when the import of a module, the following steps are performed as follows

If it is import a, check whether a is already in sys.modules, if any, do not load, if not, create a module object for a, and load a

If it is from a import B, first create a Module object for a, then resolve a, looking for B and filling in the __dict__ of a

Nested import

In the import module, we may worry that a module will not be import multiple times, fake with a,b,c three modules, a need to import B and c,b and import C, so that a will be executed to two times import C, once the import itself, The import is performed at import b at a time, but according to the import step mentioned above, the module has been loaded at the second import, so the import is not repeated.

But the following situation will be an error

#filename: A.pyfrom B import bbclass aa:pass #filename: b.pyfrom A import Aaclass Bb:pass

At this point, whether the execution of a.py or b.py will throw importerror exceptions, assuming we are performing a.py, the reason is as follows

File a.py executes from B import BB, the b.py is scanned first, and a module object is created for B in the namespace of a, attempting to find BB from B

Scan b.py The first line executes from A import AA, and then scans the a.py

Scan a.py the first line to execute from B import BB, because step 1 has created a module object for B, so will be directly from the B module object of the __dict__ to get BB, when it is obvious that BB is not obtained, and throws an exception

There are two ways to solve this situation,

Change from B import BB to import B, or change from a import AA to import A

Swap two lines of code in a a.py or b.py location

In short, import needs to be aware of, as far as possible when needed to import

Import of the package

When there is a __init__.py file in a directory, the directory is a python package

Import Package and import single file is the same, we can analogy:

When you import a single file, the classes, functions, and variables in the file are available as import objects

When you import a package, the packets in the package, the files, and the classes, functions, and variables in the __init__.py can be used as import objects.

Suppose you have the following directory structure

pkg├──__init__.py└──file.py

The contents of __init__.py are as follows

argument = 0class A:pass

It is OK to execute the following statements in the same directory as the PKG.

>>> Import pkg>>> Import pkg.file>>> from pkg import file>>> from pkg import a>> > From pkg Import argument

But the following statement is wrong

>>> Import pkg. A>>> Import Pkg.argument

Error importerror:no module named XXX, because when we execute import a.b,a and B must be module (file or package)

Relative Import and Absolute import

The absolute import format is import a.b or from A import B, and the relative import format is from. Import B or from: A import B,. Represents the current module,.. Represents the upper module, ... Represents upper-level modules, and so on. When we have multiple packages, there may be a need to import the contents of another package from one package, which produces an absolute import, which is often the most prone to errors, or a concrete example to illustrate

The directory structure is as follows

app├──__inti__.py├──mod1│├──file1.py│└──__init__.py├──mod2│├──file2.py│└──__init__.py└──start.py

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

app/mod1/file1.py content is from: MOD2 Import File2

For ease of analysis, we added print __file__ to the first line of all PY files (including __init__.py), __name__

Now the relative import is used in the app/mod1/file1.py, we execute Python file1.py under app/mod1 or execute Python mod1/file1.py under the app to be error valueerror:attempted Relative import in Non-package

Execute python-m mod1.file1 or Python start.py under app will error valueerror:attempted relative import beyond TopLevel package

For specific reasons, let's take a look at some of the rules when importing modules

In the absence of a clearly specified package structure, Python is based on __name__ to determine the structure of a module in the package, if it is __main__ itself is a top-level module, there is no package structure, if it is A.B.C structure, then the top-level module is a.

Basically follow the same principle

In the case of an absolute import, a module can only import its own submodule or the same level of modules and its submodules as its top module

In the case of a relative import, a module must have a package structure and can only import modules inside its top-level module

The directory structure is as follows

A├──b1│├──c1││└──file.py│└──c2└──b2

Where a,b1,b2,c1,c2 are packages, here in order to demonstrate simply not listing __init__.py files, when file.py's package structure for a.b1.c1.file (note, is based on __name__, rather than the directory structure of the disk, When executing file.py in different directories, the corresponding package directory structure is not the same, the following absolute import can be used in file.py

Import A.b1. C2import A.B2

And the following relative imports

From.. Import C2from ... import B2

Under what circumstances will File.py's package structure be a.b1.c1.file, as in the next two

Perform python-m a.b1 in the upper directory of a. C1.file, the package structure is explicitly specified at this time

Set up file start.py in the upper directory of a, import a.b1 in start.py. C1.file, then executes the Python start.py, at which time the package structure is based on the file.py __name__ variable

Then look at the two cases of error, the first to execute Python file1.py and Python mod1/file1.py, at this time file.py __name__ for __main__, that is, it is the top module itself, and there is no package structure, so will error

In the second case, when executing python-m mod1.file1 and Python start.py, the former explicitly tells the interpreter that MOD1 is the top-level module, which needs to be imported file1 and file1.py __name__ For Mod1.file1, the top-level module is also mod1, so the from is executed in file1.py. MOD2 Import file2 Error, because MOD2 is not inside the top module MOD1. Through the error stack can be seen, not in start.py absolute import times wrong, but in file1.py relatively import the error

So how can I do it correctly, there are two methods, one is to execute python-m app.mod1.file1 in the top-level directory of the app, the other is to change the directory structure, put all the packages in a large package, as follows

   App├──pkg│├──__init__.py│├──mod1││├──__init__.py││└──file1.py│└──mod2│├──__init__.py│└──file2.py└──start . py

start.py content into import pkg.mod1.file1, then execute Python under App start.py

Summarize

The above is the entire content of this article, I hope that the content of this article on everyone to learn or use Python can bring some help, if there is doubt you can message exchange.

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.