Python module
1, Basic concepts
What is a module?
Modules are a collection of functions, which are divided into three categories:
- Built in module
- Third party modules
- Custom module
There are four types of modules:
- Written in Python Py file (a python file itself is a module, the file name is m.py, and the module name is m)
- C or C + + extensions that have been compiled as shared libraries or DLL s
- A folder that organizes a series of modules together (Note: there is a _init _. Py file under the folder, which is called package)
- Built in modules written in C and linked to the python interpreter
Why use modules?
- Built in and third-party modules can be used without definition. This doctrine can greatly improve their development efficiency.
- User defined modules can extract the functions shared by all parts of the program and put them into one module for everyone to share. The advantage is that the code redundancy is reduced and the program organization structure is clearer.
Two, the use of modules
Definition module
File name: foo py
Document content:
print('modular foo Check in') x = 1 def get(): print(x) def change(): global x x = 0
We have now defined a module named foo.
Note: the naming of custom modules should be in the format of pure lowercase + underline
Import module
To reference the functions in the foo module in another py file, you need to use import foo import.
import foo # Module foo to check in
We can see that the module was successfully imported and the module code was executed.
When we need to import multiple modules, we can import multiple modules in one line with commas as as separators:
import time, foo, m # However, this is not recommended because we have specifications for importing modules.
Specification of import module:
The modules we import may include python built-in modules, third-party modules and custom modules. In order to distinguish them clearly, we usually import modules at the beginning of the file and classify them. The import of one type of module is separated from the import of another type by a blank line. The import order of different types is as follows:
- python built-in module
- Third party module
- Programmer defined module
import time import sys import Third party 1 import Third party 2 import Custom module 1 import Custom module 2 import Custom module 3
What happens when a module is imported for the first time (repeated import is invalid)?
-
Execute the source file code of the module
-
Generate a new namespace to store the name generated during the execution of the module's source file
-
Get a name foo in the namespace where the current executable file is located. This name points to the newly created module namespace. To reference the name in the module namespace, you need to add this prefix, as follows:
import foo a = foo.x # The value of the variable x in the reference module foo is assigned to the name a in the current namespace foo.get() # Call the get function of module foo foo.change() # Call the change function in the module foo print(foo.x) # Operation results: # Module foo to check in # 1 # 0
After the module is imported for the first time, the behavior of repeatedly importing the same module is to directly reference the module namespace generated by the first import, and the code will not be executed repeatedly.
References after importing modules
-
"Module name. Name" refers to the value corresponding to the name of a module. It will not conflict with the name in the current namespace.
import foo x = 1111111111111 print(x) print(foo.x) # Operation results: # Module foo to check in # 1111111111111 # 1
-
Whether viewing or modifying, the operation is the module itself, regardless of the calling location. (the interrelationship of namespaces is determined at the time of definition)
import foo x = 1111111111111 foo.get() # 1 foo.change() # foo. The x in py has been modified foo.get() # 0
Other import syntax
-
import module name as custom name
The method of importing modules only by import must be prefixed with "module."
Advantage: it certainly does not conflict with names in the current namespace
Disadvantages: prefixing is troublesome
import module name as custom name:
Aliasing is usually used to simplify the code when the imported name is too long. In addition, aliasing the imported name can well avoid conflicts with the current name.
import foo as f f.get() # 1
-
You can import modules within functions
def func(): import foo
-
from...import...
From... Import... Is basically the same as the import statement. The only difference is that after importing a module with import foo, the names in the referenced module need to be added with foo As a prefix; In the form of from foo import x, get and change, you can directly reference the name in the module foo in the current execution file, as follows:
from foo import x,get,change # Import x, get and change in the module foo into the current namespace a=x # Directly assign the memory address pointed by X in the module foo to a in the global namespace of the current file (let a point to the memory address pointed by x) get() # Directly execute the get function in foo change() # Even if there is an x with the same name in the current file, the x in the source file is still modified
If the same name exists in the current namespace, the later defined name will overwrite the previously defined name, as follows:
x = 'pleasantly surprised' from foo import x print(x) # 1
from... import... Three things also happen:
-
Generate a module namespace
-
Run foo Py, throw all the names generated in the running process into the module namespace
-
Generate a name in the namespace of the current file, which points to the same memory address as the same name in the module namespace
from foo import x # x = memory address of module foo value 1 from foo import get from foo import change print(x) # 1 print(get) # <function get at 0x000002696B0B4700> print(change) # <function change at 0x000002696B0B4670> x = 333333333 print(x) # 333333333 change() get() # 0 print(x) # 333333333
from foo import x # x = memory address of module foo value 1 from foo import get from foo import change print(x) # 1 change() # Only the value of x in the module foo is changed. The bound value of x in the current file namespace when importing the module is 1. Changing the bound value of x in the module will not affect x in the current file namespace. get() # 0 print(x) # 1
Use from... Import... To import modules without prefixes
Advantages: more streamlined code
Disadvantages: easily confused with the current namespace
from... Import * all names in the import module:
from foo import * print(x) print(get) print(change) # Operation results: # Module foo to check in # 1 # <function get at 0x000001B59AD14160> # <function change at 0x000001B5AB774700>
If we need to reference too many names in the module, we can use the above import form to save code, but it should be emphasized that * can only be imported at the top level of the module, which is illegal in the function. And the * method will bring a side effect, that is, we can't figure out which names are imported from the source file to the current file, which is likely to conflict with the name of the current location.
So the module writer can define _inhis own file_ all_ _ Variable is used to control the name range represented by *:
# In foo Add to py: _ _all_ _ = ['x'] # What are the names represented by control *
Import in current file:
from foo import * # At this time, * only represents x print(x) # 1 print(get) # Error: NameError: name 'get' is not defined print(change) # Error: NameError: name 'change' is not defined
Use as alias:
from foo import get as g g() # Operation results: # Module foo to check in # 1
-
3, Two uses of a Python file
A Python file serves two purposes
- Run as a program
- Imported as a module
What is the difference between the two “_ _name_ _”
- When foo When py is run_ name_ _ The value of is' _ '_ main_ _ ’
- When foo When py is imported as a module_ name_ _ The value of is' foo '
if __name__ == '__main__': print('python file run') # Run foo directly Py file output this sentence else: print('The file is imported as a module') # As a module, import and output through import
4, Priority of module lookup
Whether import or from... Import involves finding when importing modules
Priority of discovery:
- Memory (built-in module)
- Hard disk: according to sys Find the modules to be imported in the order of the paths stored in path
When importing a module, if the module has been loaded into memory, it will be referenced directly. Otherwise, the built-in module will be searched first, and then sys. Net will be retrieved from left to right The path defined in path until the file corresponding to the module is found, otherwise an exception is thrown.
sys.path is also called the search path of the module. It is a list type:
import sys print(sys.path) # Value is a list that holds a series of pairs of folders # The first folder is the folder where the current execution file is located
If you cannot find the module you want to import, you can add the absolute path of the folder where the module is located to sys Path list
import sys # Find foo Py put foo The absolute path of the folder of Py is added to the environment variable sys.path.append(r'/Users/user/PycharmProjects/Demo/test/8.20')
Note: this addition is temporary and will be restored after the program runs.
Use sys Modules view the modules that have been loaded into memory
import sys # print('foo' in sys.modules) # False print(sys.modules)
5, Write the specification of the module
When writing the py file of the module, we need to remind ourselves that the file is not only for ourselves, but also may be used by others. Therefore, the readability and maintainability of the code are very important. Therefore, we'd better write a module according to a unified specification, as follows:
"The module is used to..." #Document description of the module import sys # Import module x=1 # Define global variables. If it is not necessary, it is best to use local variables, which can improve the maintainability of the code, save memory and improve performance class Foo: # Define the class and write the comments of the class 'Class Foo is used to...' pass def test(): # Define the function and write the comments of the function 'Function test is used to...' pass if __name__ == '__main__': # main program test() # When executed as a script, execute the code here