Python-based packages and modules

Source: Internet
Author: User

This article and everyone to share is mainly python in the package and module-related content, come together to see it, hope to learn Python to help you.

Summary

1. For reuse and better maintenance of code, Python uses modules and packages; a python file is a module that is a special directory (containing the __init__.py file) of the organization module.

2. Module search path, Python interpreter search for modules in a specific directory, run-time Sys.path that is the search path.

3. Import The module using the Import keyword and note the relationship between import * and __all__ .

1. Module and Import

A module is a file containing Python definitions and statements

A Python module is a file that contains definitions and statements, with the name of the module plus the . py suffix.

1.1 Born for reuse

Suppose there is a function or class that accomplishes a particular function and is useful. To use this feature, you have to copy the code into every file you need to use. Repetitive code is the taboo of programming, if the functional implementation needs to be modified, will have to modify every occurrence of the place, which is anti-human.

Reuse can be a good solution to this problem, in fact, functions, classes and other structures to some extent also provides convenience for reuse.

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

1.2 Importing Modules

Import The module using the Import keyword (the module needs to be in the search path):

1. import SYS; the underlying 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 import names from sys

Import-only-once

Module Import only once this behavior is a substantial optimization in most cases, in the same interpreter lifetime, importing the same module multiple times with an import statement, and importing occurs only once.

This can be demonstrated by adding an output statement to the module.

Import * and __all__

Using Import * may contaminate the namespace of the current module and import some names that do not need to be referenced. Therefore, it is not recommended.

In fact, the canonical third-party module provides a common interface to the module that exposes the interfaces available to the module. The public interface is defined by a list of modules named __all__ .

For example, define a module named mtest1 :

__all__ = [' test1 ', ' test12 ']

def test1 ():

Print (' test1 ')

def test11 ():

Print (' test11 ')

def test12 ():

Print (' test12 ')

To use the full import method:

>>> Form Mtest1 Import *

>>> dir ()

>>> [' __annotations__ ', ' __builtins__ ', ' __doc__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' Test1 ', ' test12 ']

You can see that the function test11 () is not imported, which is what __all__ does.

2. Package and its construction

To better organize the modules, group the modules into packages.

2.1 Package is a special module

From the file system, the package is the directory where the module resides. In order for the Python interpreter to differentiate its generic directory as a package, the package must contain a file (module) named __init__.py directly.

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

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

PI = 3.14

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

Import Constantsprint (constants. PI)

2.2 Building Packages

If you are building a package named drawing that contains shapes and colors modules, you need to create directories and files:

~/python add to the directory in the search path

~/python/drawing Package Directory (drawing package)

~/python/drawing/__init__.py Package code (drawing module)

~/python/drawing/colors.pycolor Module

~/python/drawing/shapes.pyshapes Module

Assume that ~/python has been used as the search directory. According to this setting, the following import statements are valid:

1. Import Drawing # Importing drawing package (i.e. __init__.py module)

2. Import drawing.colors # Imports the colors module, referencing it using the Drawing.colors.attr method

3. From drawing Import Shapes # importing Shapes module

__all__ Variable

Similar to the __all__ variable of the module, the __all__ variable of the package determines the sub-modules that are imported using the From Pack import * .

As above drawing package of __init__.py file contents are as follows:

__all__ = [' Colors ']

Then using the From drawing import * only imports the colors module.

3. Search Path

Now I have finished writing a very useful module and passed the test. So how do you make this module available? That is, how to make the module capable of importing into other modules.

3.1 Search Module

When importing a module using the import statement, the Python interpreter searches for the module in the following ways:

1. First search built-in module

2. Last search variable sys.path list of paths provided

Sys.path is initialized at the start of the interpreter from the following location:

1. Current Script path

2. Environment variable PYTHONPATH the specified path collection

3. Install the default path

After the Sys.path initialization is complete, it can be modified at run time.

3.2 Making the module available

So now to make the module available, one is to place it under an existing search path, and the second is to specify that the module is located on the path to the search path.

In general, if you choose the first method, we place the module under the \lib\site-packages of the Python installation path, which is designed to install third-party modules. As the README file in this directory shows:

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

If you choose the second method, add the directory of the module directly to the environment variable PYTHONPATH .

It is important to note that you can create a new file named user_lib.pth under the \lib\site-packages path, a path that needs to be searched, one row at a A, or you can add the specified path to the search directory:

Source: Blog Park

Python-based packages and modules

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.