Home  >  Article  >  Backend Development  >  Python basics-detailed explanation of packages and modules

Python basics-detailed explanation of packages and modules

PHP中文网
PHP中文网Original
2017-06-20 16:49:311879browse

Python Basics - Packages and Modules

Written in front

Unless otherwise stated, the following is based on Python3

Abstract

  1. In order to reuse and better maintain code, Python uses modules and packages; a Python file is a module, and a package It is a special directory for organizing modules (including the __init__.py file).

  2. Module search path, PythonThe interpreter searches for modules in a specific directory, and sys.path is the search path when running.

  3. Use the import keyword to import the module, pay attention to the relationship between import * and __all__.

1. Modules and imports

A module is a file containing Python definitions and statements

PythonA module is a file containing definitions and statements. The file name is the name of the module plus the .py suffix.

1.1 Born for reuse

Suppose there is a function or class that performs a specific function and is easy to use. In order to use this feature, you have to copy this code into every file you need to use. Duplicate code is a taboo in programming. If the function implementation needs to be modified, every place where it appears will have to be modified. This is anti-human.

Reuse can solve this problem very well. In fact, structures such as functions and classes also provide convenience for reuse to a certain extent. In

Python, a series of related functions, classes, etc. are organized in a file, and each file is a Python module.

1.2 Import module

Use the import keyword to import the module (the module needs to be in the search path):

  1. import sys ;Basic import statement.

  2. import sys as system; alias the imported name.

  3. from sys import path; Import module specific elements.

  4. from sys import *;Import all importable names from sys

import-only-once
The behavior of importing a module only once is a substantial optimization in most cases. In the same interpreter life cycle, the same module is imported multiple times using the import statement. Modules, imports only happen once.

This can be proven by adding output statements to the module.

import * and __all__
Using import * may pollute the namespace of the current module. Import Some names do not need to be quoted. Therefore its use is not recommended.

In fact, a standardized third-party module will provide a module public interface, exposing the interfaces available to the module. Public interfaces are defined by a list of module names __all__.

If you define a module named mtest1:

__all__ = ['test1', 'test12']def test1():print('test1')def test11():print('test11')def test12():print('test12')

Use all import methods:

>>> form mtest1 import *>>> dir()>>> ['__annotations__', '__builtins__', '__doc__', '__loader__','__name__', '__package__', '__spec__', 'test1', 'test12']

You can see that the function test11() has not been imported. This is the role of __all__.

2. Packages and their construction

In order to better organize modules, modules are grouped into packages.

2.1 Package is a special module

From the file system point of view, the package is the directory where the module is located. In order for the Python interpreter to treat it as a package, the package must directly contain a file (module) named __init__.py.

A package is basically another type of module, except that it can contain other modules and packages. As a module, the content of a package is actually the content of the file __init__.py (module).

For example, for a package named constants, the file constants/__init__.py is as follows:

PI = 3.14

Then the package can be constants is treated as a normal module:

import constantsprint(constants.PI)
2.2 Building the package

If you want to build a package named drawing, It contains the shapes and colors modules. You need to create the following directories and files:

##~/python/drawing/shapes.pyshapes module

假设已经将~/python作为搜索目录。依照这个设置,下列导入语句都是合法的:

  1. import drawing # 导入drawing包(即__init__.py模块)

  2. import drawing.colors # 导入colors模块,使用drawing.colors.attr的方式引用

  3. from drawing import shapes # 导入shapes模块

__all__变量
与模块的__all__变量相似,包的__all__变量决定了使用from package import *导入的子模块。

如以上drawing包的__init__.py文件内容如下:

__all__ = ['colors']

那么使用from drawing import *只会导入colors模块。

3. 搜索路径

现在已经编写完了一个很好用的模块,并且通过了测试。那么如何让这个模块可用呢?即如何让这个模块具备可导入到其他模块的能力。

3.1 搜索模块

当使用import语句导入模块时,Python解释器通过以下方式搜索模块:

  1. 首先搜索built-in模块

  2. 最后搜索变量sys.path提供的路径列表

sys.path在解释器启动时从以下位置初始化:

  1. 当前脚本路径

  2. 环境变量PYTHONPATH指定的路径集合

  3. 安装默认路径

sys.path初始化完成后,可以在运行时修改。

3.2 让模块可用

那么现在若要使模块可用,一是将其放置到已有的搜索路径下,二是指定模块所在路径为搜索路径。

一般情况下,若选择第一种方式,我们将模块放置到Python安装路径的\lib\site-packages下,这个目录是专门用来安装第三方模块的。正如该目录下的README文件展示的那样:

This directory exists so that 3rd party packages can be installed here. Read the source for site.py for more details.

若选择第二种方式,直接将模块所在目录加入到环境变量PYTHONPATH中即可。

值得注意的是,可以在\lib\site-packages路径下新建一个名为user_lib.pth的文件,内容是需要搜索的路径,一行一个,也可以将指定路径加入到搜索目录中:

Python basics-detailed explanation of packages and modules

File/Directory Description
~/python Directory added to the search path
~/python /drawing Package directory (drawing package)
~/python/drawing/__init__.py Package code (drawing module)
~/python/drawing/colors.py color module

The above is the detailed content of Python basics-detailed explanation of packages and modules. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn