module
module definition
- A module is a Python file that defines many functions, classes, variables, etc.
- A complete large-scale python program is organized in the form of modules and packages.
Function of module
- Modules allow you to logically organize your Python code snippets.
- Assigning relevant code to a module can make your code better used and easier to understand.
- Modules can define functions, classes and variables, and modules can also contain executable code.
- It can avoid the conflict between function name and variable name. Variables and functions with the same name can be stored in different modules.
- The system and third-party module s are used.
Classification of modules
Usually, the standard modules and third-party modules in Python are called libraries. Libraries are just an understanding concept, emphasizing their functionality. In Python, modules and packages with certain functions can be called libraries. The module is composed of many functions. The package is composed of many modules. The library can also contain packages, modules and functions.
- Standard module (Library), provided with python interpreter.
- Third party modules (Libraries) need to be installed through install.
- Custom module
Use of modules
- The module needs to be import ed before use.
import statement
- The way of branch writing is more clear and recommended.
- When using variables inside the module, you need to add the module name.
- A py file may contain multiple modules, including built-in modules, third-party modules and custom modules. In order to increase code readability and better comply with the PEP8 specification (the specification for writing code in python Development), modules are usually imported at the beginning of the file, and three different modules are separated by blank lines.
# Format 1: comma separated import module1[, module2[,... moduleN] # Format 2: Branch write import module1 import module2 ...
from... import statement
- There is no need to add module name prefix when using.
from modname import name1[, name2[, ... nameN]]
Advantages and disadvantages | import module name | import module name from |
---|---|---|
advantage | It certainly does not conflict with the name of the current namespace | Without prefix, the code is simpler |
shortcoming | Prefixing makes the code not concise | It is easy to be confused with the name of the current namespace, and the attribute under the module under the IDE is not easy to prompt |
from... import * statement
- Import all contents of a module into the current namespace.
- It takes up too much memory and should not be used too much.
import...as ...
- When the imported module name is too long, you can use aliasing to simplify the code.
- Aliases are a good way to avoid conflicts with names in the namespace of the current file.
import modname as Variable name
# example. Content in PY __all__ = ["a"] a = 1 b = 2 # Imported statement content from simple import * print(a) print(b) result: NameError: name 'b' is not defined
Example of import statement
from random import randint import time import math as mt from numpy import * print(randint(1,5)) print(time.time()) print(mt.sqrt(9)) print(list(arange(0.1,1))) result: 1 1651757322.7786858 3.0 [0.1]
package
Definition of package
- The package is composed of module files, and many module files with related functions are structurally combined to form a package.
- In a nutshell, a package is a folder, but init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init. Init Py file, the contents of which can be empty. init.py is used to identify that the current folder is a package.
- The package structure makes the files with the same module name under different packages no longer conflict.
- The module and package name should be different from the built-in module name as far as possible, otherwise the built-in module will be overwritten
Package organization chart
Import of modules in package
- When importing the contents in the package, the contents in the package will be executed first__ init__.py file.
from import
from package_name import module_name from package_name.module_name import * from package_name.module_name import name1, name1... from package_name import module_name as name
Absolute path import
- Write the full path based on the project, package subpakage. moudule.
- Recommended.
└── project1 | ├── package_A | │ ├── __init__.py | │ ├── module_A.py | │ └── module_B.py | │ └── CurrentProgram.py | └── package_B | ├── __init__.py | ├── module_C.py | ├── module_D.py | └── subpackage_B | └── module_E.py For example, in module_B Import in module_E,The method is from package_B.subpackage_Bimport module_E
Relative path import
- You can import modules of the same level (in the same directory) in the file Module name import.
- The current module(name=main) cannot use relative path to import the same level module, because the relative path imports dependent files__ name__, If it is the current execution file, name=main, so__ package__ Will be set to None, and the relative reference is dependent__ package__ The relative reference position cannot be found.
└── project1 | ├── package_A | │ ├── __init__.py | │ ├── module_A.py | │ └── module_B.py | │ └── CurrentProgram.py module_B Import in module_A Medium test method, from.module_B import test
init.py file
- The package ID in Python cannot be deleted.
- Definition__ all__ Used to control the import of * mode.
- When importing a package, it is executed first__ init__ This module.
- You can put some initialization code (it is not recommended to write python module in ___ init. Py, but you can create another module in the package to write it, so as to ensure that _. Py is as simple as possible)
__ all__ Restrict import
- If you want to import all modules in the package for use through the from package import *, you need to__ init__ Add in__ all__= [module name], otherwise none of the modules will be executed.
- If it is an ordinary from module import *, then__ all__= [] if not, then all imports, if any, are only exposed in [].
- It only works in the import method with * and other import methods are not affected__ all__ The impact of.
Circular import
Circular import definition
- The problem of circular import refers to importing another module during the loading / importing process of one module, and the name of the first module is imported back in the other module. Since the first module has not been loaded, the reference fails and an exception is thrown.
Circular import example
""" 1. When modules Module execution test.work import w1 When you want to import, run to work.py In, but see from test.modules import m1, and modules Not yet m1,You have to put the first line test.work import w1 The definition cannot be reached until the execution is completed m1 Statement of m1 = "modules1",So errors will occur. 2. Similarly, yes work So is the module. """ modules.py content from test.work import w1 m1 = "modules1" print("-----------Print work Medium w1----------", w1) work.py content from test.modules import m1 w1 = "work" print("-----------Print modules Medium m1----------", m1) result:report errors
Circular import solution
The import statement is placed before the variable or function used
modules.py content m1 = "modules1" from test.work import w1 print("-----------Print work Medium w1----------", w1) work.py content w1 = "work" from test.modules import m1 print("-----------Print modules Medium m1----------", m1)
The import statement is placed in the function
- Put import in the definition function so that it will not be executed during import, but only when the function is called.
modules.py content m1 = "modules1" def func_modules(): from test.work import w1 print("-----------Print work Medium w1----------", w1) work.py content w1 = "work" def func_work(): from test.modules import m1 print("-----------Print modules Medium m1----------", m1)