Python Modules and Packages

Source: Internet
Author: User
Tags aliases floor function

Module: A module is a file containing Python definitions and declarations, and the filename is the suffix of the module name plus the. Py.

In fact, the import loaded module is divided into four general categories:

1 code written using Python (. py file)

2 C or C + + extensions that have been compiled as shared libraries or DLLs

3 packages for a set of modules

4 built-in modules written and linked to the Python interpreter using C

First, import statements

The import statement acts as a means of importing a module, which can appear anywhere in the program.

Usage:

Import the module using the import statement, the import statement syntax is as follows:

Import Module keyword modules name

Use methods such as:

Import Math #入导math模块

Math.floor () #调用math模块中的floor () function

If you want to import multiple modules at the same time, you only need to delimit them with commas before the module name:

Import Module1,module2,module3 .....

The method of importing multiple modules at the same time is less readable and understandable to beginners than the first. Therefore, when you want to import more than one module, it is recommended to use the first way, each module is a separate import, you may feel that the operation is troublesome, but easy to understand.

Alias for module name, equivalent to M1=1;M2=M1

Import spam as SM

Print (Sm.money)

Second, Form...impot statement

The Form...impot statement is also a way to import the module, or, more specifically, the specified function method within the specified module.

From-import statement syntax

From module import name keyword block Name keyword method name

For example, the floor function method in the math module of the onboarding function:

From math import Floor

Form...impot use methods such as:

From math import Floor #导入math模块中的floor函数方法

Floor () #调用floor () function method

Third, module search path

The Python interpreter automatically loads some modules at startup, You can use Sys.modules to view the first time a module is imported (such as spam), the module will first check whether it has been loaded into memory (the current execution of the file's namespace corresponds to the memory), if there is a direct reference, if not, the interpreter will find the same name of the built-in module, if not found, from Sys.path to Look for the spam.py file in the list of directories. So the summary module lookup order is: In memory loaded modules, built-in module->sys.path path contains modules

The value of the Sys.path initialization is derived from:

The directory containing the input script (or the current directory if no file is specified).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

The installation-dependent default.

It is important to note that our custom module names should not be the same as the system's built-in modules. Although it is said every time, there will still be people who make mistakes.

After initialization, the Python program can modify the Sys.path, and the path is placed prior to the standard library being loaded.

Import sys
Print (Sys.modules)

{' Builtins ': <module ' builtins ' (built-in), ' sys ': <module ' sys ' (built-in);, ' _frozen_importlib ': < Module ' _frozen_importlib ' (frozen), ' _imp ': <module ' _imp ' (built-in), ' _warnings ': <module ' _warnings ' ( built-in), ' _thread ': <module ' _thread ' (built-in), ' _weakref ': <module ' _weakref ' (built-in);, ' _ Frozen_importlib_external ': <module ' _frozen_importlib_external ' (frozen), ' _io ': <module ' io ' (built-in)  , ' Marshal ': <module ' Marshal ' (built-in), ' NT ': <module ' NT ' (built-in), ' winreg ': <module ' winreg ' (built-in), ' Zipimport ': <module ' zipimport ' (built-in);, ' encodings ': <module ' encodings ' from ' c:\\ python36\\lib\\encodings\\__init__.py ', ' Codecs ': <module ' codecs ' from ' c:\\python36\\lib\\codecs.py '; _codecs ': <module ' _codecs ' (built-in), ' encodings.aliases ': <module ' encodings.aliases ' from ' C:\\Python36\ \lib\\encodings\\aliases.py ';, ' encodings.utf_8 ': <module' Encodings.utf_8 ' from ' c:\\python36\\lib\\encodings\\utf_8.py ', ' _signal ': <module ' _signal ' (built-in); ' __main__ ': <module ' __main__ ' from ' f:/python/assignment/4day/2.py ', ' encodings.latin_1 ': <module ' Encodings.latin _1 ' from ' c:\\python36\\lib\\encodings\\latin_1.py ', ' io ': <module ' io ' from ' c:\\python36\\lib\\io.py '; ABC ': <module ' abc ' from ' c:\\python36\\lib\\abc.py ';, ' _weakrefset ': <module ' _weakrefset ' from ' c:\\python36 \\lib\\_weakrefset.py ', ' site ': <module ' site ' from ' c:\\python36\\lib\\site.py ';, ' OS ': <module ' OS ' from ' c:\\python36\\lib\\os.py ', ' errno ': <module ' errno ' (built-in), ' stat ': <module ' stat ' from ' c:\\ python36\\lib\\stat.py ', ' _stat ': <module ' _stat ' (built-in), ' Ntpath ': <module ' Ntpath ' from ' c:\\ python36\\lib\\ntpath.py ', ' genericpath ': <module ' Genericpath ' from ' c:\\python36\\lib\\genericpath.py ' > , ' Os.path ': <module ' Ntpath ' from ' c:\\python36\\lib\\ntpath.py ' &Gt;, ' _COLLECTIONS_ABC ': <module ' _collections_abc ' from ' c:\\python36\\lib\\_collections_abc.py ';, ' _ Sitebuiltins ': <module ' _sitebuiltins ' from ' c:\\python36\\lib\\_sitebuiltins.py ';, ' sysconfig ': <module ' Sysconfig ' from ' c:\\python36\\lib\\sysconfig.py ' >}  #排在前的目录, priority to be searched

Iv. Import of packages

A package is a way to organize the Python module namespace by using the '. Module name '.

1. Whether it is an import or From...import form, it is the first time to be alert when you encounter a dot in an imported statement (rather than in use): This is the import syntax for packages

2. Packages are directory-level (folder-level), folders are used to form a py file (the essence of the package is a directory containing __init__.py files)

3. Import the file, the resulting namespace name from the file, import package, the name of the resulting namespace is also derived from the file, that is, the __init__.py under the package, the import package is the essence of the import of the file

Emphasize:

1. In Python3, even if there is no __init__.py file under the package, import package will still not error, and in Python2, the package must have the file, or import packet error

2. The purpose of creating the package is not to run, but to be imported to use, remember that the package is just a form of the module, the package is a module

glance/#Top-level Package

├──__init__.py #Initialize The Glance Package

├──api #Subpackage for API

│├──__init__.py

│├──policy.py

│└──versions.py

├──cmd #Subpackage for CMD

│├──__init__.py

│└──manage.py

└──db #Subpackage for DB

├──__init__.py

└──models.py

#文件内容

#policy. py

Def get ():

Print (' from policy.py ')

#versions. py

def create_resource (conf):

Print (' From version.py: ', conf)

#manage. py

def main ():

Print (' from manage.py ')

#models. py

def register_models (engine):

Print (' From models.py: ', engine)

Under Glance __init__.py add:

From Glance.api.policy Import get

From glance.api.versions import Create_resource

From glance.cmd.manage Import Main

From Glance.db.models import Register_models

Precautions

1. Import statements related to packages are also divided into imports and from ... import ... Either way, regardless of location, you must follow a principle when importing: any point on the import, the left side must be a package, otherwise illegal. Can carry a series of points, such as Item.subitem.subsubitem, but all must follow this principle.

2. For import, there is no such restriction when used, the left side of the point can be a package, a module, a function, a class (they can all call their own properties in the way of a point).

3. Compare the application scenarios for import item and from item import name:

If we want to use name directly then we must use the latter.

V. Absolute import vs. relative import

Our top package glance is for others to use, and then within the glance package will also have each other to import each other needs, this time there are absolute import and relative import two ways:

Absolute import: Starting with glance

Relative import: With. Or. (can only be used in one package and not in different directories)

For example: We want to import glance/cmd/manage.py in glance/api/version.py

In glance/api/version.py

#绝对导入

From Glance.cmd Import Manage

Manage.main ()

#相对导入

From.. CMD Import Manage

Manage.main ()

Test Result: note must be tested in glance peer files

From GLANCE.API import versions

Modify the above with relative imports:

From. Api.policy Import Get

From. Api.versions Import Create_resource

From. Cmd.manage Import Main

From. Db.models Import Register_models

Python Modules and Packages

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.