Detailed explanation of Python modularization module of Modules and package of Packages

  • 2021-11-24 01:56:08
  • OfStack

Directory Introduction Python Modules Module Import Module ① Import the whole module ② Import the specific function in the module ③ Import all the functions in the module to the imported module 1 alias Run separately Module Accelerate Module Load Python Packages Package Reference Package (Package) Submodule Function or Variable Use Relative Path Reference Package and Module Use __all__ Provide Package Display Package your own Package and distribute the Package summary in the python community

Introduction

When you first started python, terms such as modular programming, module and class library were often not easy to clarify. In particular, Modules (module) and Packages (package) are easily confused and wrong when referenced by import.

In fact, the functions (Function), classes (Class), modules (Module) and package libraries (Package) in Python are all designed to realize modular references and make the organization of programs clearer and more organized.

Typically, functions, variables, and classes are stored in a. py file called a module (Module), and a set of module files constitutes a package (Package). By storing functions, variables and classes in an independent. py file, the details of code implementation can be hidden, different code blocks can be reorganized, separated from the main program, the logic of the main program can be simplified, and the readability of the main program can be improved. With package and module files, you can reuse them in different programs, and you can use third-party dependency libraries developed by others.

Python Modules Module

The Modules2 module is a file that contains Python definitions and statements. The file name with the suffix. py is the module name.

Within a module, the name of the module can be represented by the global variable __name__ (string).

For example, we created an fibo. py file with the following contents:


# Fibonacci numbers module
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()
def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Here, fibo. py is a module, and fib and fib2 are functions in fibo module.

Import module

If we want to use the fibo module in other programs, we can import it in the following three ways:

Import the whole module


#import module_name
import fibo

You can use any one of these functions using the following syntax:


#module_name.func()
fibo.fib(10)

Note to ⭕: The module name + period cannot be omitted here.

② Import specific functions in the module


#from module_name import function_name
from fibo import fib, fib2
fib(10)

If you use this syntax, you don't need to use the module name + period when calling the function.

Because the functions fib and fib2 have been explicitly imported in the import statement, you only need to specify their name when you call it.

Import all functions in the module


#from module_name import *
from fibo import *
fib(20)

This method imports all functions except names that start with an underscore (__).

Note ⭕: In most cases, * is generally not recommended because it may introduce an unknown set of names into the interpreter and often results in poor code readability.

Give an alias to the imported module 1


# import module as m
import numpy as np
a = np.arange(100)

Use as to give an alias to the import module 1, which simplifies the calling writing in the code.

Run module separately

If we want to test the module separately, we can add the following code to the module, which can be used as both a script and an importable module:


if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Run modules separately:


python fibo.py 100

This parsing command line code only runs when the module is executed as a "master" file.

Accelerate module loading

To speed up module loading, Python caches the compiled version of each module (such as *. pyc) in a directory under __pycache__. For the detailed process of generating the compilation file pyc, please refer to the document PEP 3147.

Python checks the source code for modification dates based on the compiled version to see if it has expired and needs to be recompiled.

Python Packages Package

The Packages package can be understood as a container for a set of modules, and Namespace 3 is constructed in the manner of Package. Module.

In the file system analogy, you can think of packages as directories on the file system and modules as files in directories. 4

For example, A. B specifies a submodule named A in a package named B.

Using this method, we can avoid the problem of naming conflicts among several multi-module packages, which is somewhat similar to the references of namespaces such as std:: string, cv:: imread in C + +.

For example, this is an official package example that provides an sound package for sound processing:


sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              ...
__init__. py must have this file for Python to treat the directory containing it as a package (Package). __init__. py can be an empty file, or you can execute package initialization code or set the __all__ variable. formats/, effects/, filters/are sub-level 1 subpackages (Subpackage), and each subpackage also has __init__. py files. Files such as echo. py are modules in a subpackage (Module) that may contain functions, classes, or variables.

Reference module in package (Package)


from sound.effects import echo
echo.echofilter(input, output, delay=0.7, atten=4)

In this way, you can refer to functions directly without prefixing them with prebread.

Function or variable of submodule in reference package (Package)


#import module_name
import fibo
0

This loads the submodule echo and makes the echofilter () function in the submodule directly available.

The from package import item statement first tests whether item is defined in the package; If no definition is found in the package, item is assumed to be a module and an attempt is made to load it. If you still can't find item, it will lead to our common ImportError异常。

Referencing packages and modules with relative paths


#import module_name
import fibo
1

Here. You can access the package (Package) or module (Module) in the sibling directory.
Here,.. can access the package (Package) or module (Module) in the upper level 1 directory.

Provide an explicit index of packages with __all__

When we use from sound. effects import * directly, we may refer to unwanted content or lead to slow loading.

At this point, we can specify the list of module names that should be imported with * by defining a _all__ list in __init__.py:


#import module_name
import fibo
2

This allows us to maintain a list of modules that need to be imported at import *, which is useful when releasing different versions of the package.

Package your own Package and distribute it

To package your own Package with the setuptool tool, you can refer to these two documents:

https://packaging.python.org/tutorials/packaging-projects/
How to add the necessary files and structures to create the package, how to build the package, and how to upload it to Python Package Index.

https://packaging.python.org/guides/distributing-packages-using-setuptools/
Describes the basics of how to configure, package, and distribute your own Python project.

Install Package in the python community

Note that Package in the python community usually refers to the distribution package, not the container of a set of modules in the source code (a container of modules).

Common packages can be found at PyPI: https://pypi. org/, and Packages provided by the community can be installed by using pip install.

Summarize

Modularization is to organize the relevant code into files at different levels, which is convenient for reuse and improves the readability of the code.

Functions, variables, and classes are stored in a. py file called a module (Module), and a set of module files is made up of a package (Package).

Package package or Module module can be introduced by import … or from … import …, and the upper level 1 package and module can be referenced through relative path.

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: