First acquaintance with python module

1. Process oriented programming (Theory)

Process oriented programming is like designing a product pipeline to solve problems distributed.
For example, the user registration function

  1. Get user name and password
  2. Organize into fixed format
  3. File operation write file

Simple design and clear thinking

Take an example:

def get_info():
	username = input('user name>>>:').strip()
	pwd = input('password>>>:').strip()
	if len(username)==0 or len(pwd)==0:
		print('User name or password cannot be empty')
		return
	return deal_data(username, pwd)

def deal_data(username, pwd):
	data = '{}|{}\n'.format(username, pwd)
	return save_data(data)

def save_data(data):
	with open(r'userinfo.txt', 'a', encoding='utf8') as f:
		f.wriet(data)
	
get_info()
# Simple process oriented programming user registration case

2. Module introduction

python language originated from Linux operation and maintenance, which is called glue language and package man.

  1. What is a module???
    Module: a combination of a series of functions

  2. Why use modules???
    In order to improve development efficiency (standing on the shoulders of Giants)

  3. Three sources of modules

    1. Built in module (provided with python interpreter)
    2. Third party module (written and published on the Internet by others, downloaded and reused based on the network)
    3. Custom module (self written)
  4. Four forms of modules

    1. Code written in python (. py file)

    2. C or C + + extensions that have been compiled as shared libraries or DLL s.

    3. Package (folder) that wraps a set of modules
      A package is actually a collection of multiple py files (modules).
      The bag usually contains one__ init__.py file.

    4. Built in modules written in C and linked to the python interpreter
      1. 3 key points

After learning the module, when we write a large project in the future, if we encounter some complex functions, we can first consider whether there is a corresponding module to call.

3. import sentence pattern

Note: when learning the module, you must distinguish who is the import file and who is the module file.

# The run file name is import syntax. py

import md # md, py file name, import py file module file suffix must not be added.
# If the same module is imported multiple times, it will be executed only once
"""
Let's look at the first import md What happens when the module
	1.Run import file( import Sentence pattern.py)The global namespace that generated the file.
	2.function md.py file
	3.produce md.py Global namespace, running md File internal code,
	Store all the new names in md.py Namespace for.
	4.Generates a in the import file namespace md Your name points to md.py Global namespace.
"""
# import sentence after importing the module
#	All names in the module can be used by clicking the module name,
# 	And there will certainly be no conflict.

4. from...import

from md import money
# From... Import... Importing the same module multiple times will only execute once 
"""
Occurs when importing:
	1.The global namespace of the executable file is generated first
	2.Execute the module file to generate the global namespace of the module
	3.All the names generated after execution in the module are archived in the module namespace.
	4.There is one in the executable money Points to the module namespace money The value pointed to.
"""
# from...import... Import a name by name
#	When using, you can write the name directly, but when the current namespace has the same name.
#	There will be a conflict, and the current namespace will be used.

5. Import module extension usage

  1. Alias: you can alias a module or a name in a module.

    import ssxxxxxxxxx as ssx(alias)
    
    from modddddddd import name as n(alias)
    
  2. Continuous import

    from time, os, sys, json...
    # It is recommended to write the imported module name separately (unless the two modules have similar functions or belong to the same series)
    # Recommendations are as follows:
    import os
    import sys
    import time
    import json
    
    
    from Module name import Name 1, name 2, name 3...
    
  3. General import

    from md import *
    # Import all the names in md, mainly combined with the from sentence.
    
    # At the same time, you can specify the name that can be imported when others use the * sign in the md.py file.
    __all__ = ['money', 'read1']  # The name in the list is the name in the md.py file
    
    
  4. Determine file type

    # Determine whether the py file is a module file or an execution file
    print(__name__)
    # __The name _ method returns _ main when the file is an execution file. If the file is imported as a module,
    # Returns the file name (module name)
    
    if __name__ == '__main__':
    	Code that runs as an executable
    
    """stay pycharm You can knock directly in main Press tab Press the key to automatically complete the above code"""
    

6. Circular import problem

# Run file name: Circular import. py
import m1



# Module file name: m1.py
print('Importing m1')
from m2 import y
x = 'm1'



# Module file name: m2.py
print('Importing m2')
from m2 import x
y = 'm2'


--------------------------------------
# In this way, an error will be reported when executing the run file, resulting in the problem of circular import
"""
ImportError: cannot import name 'x' from partially 
initialized module 'm1' (most likely due to a circular import)
"""

"""
In the future, when we import modules, if circular import occurs,
It shows that your program design is unreasonable.
Circular import is usually not allowed!!!!
"""
However, if you want to remedy the mistakes again and again, you can take the following methods:
	1.Exchange sequence
		Put the imported sentence patterns at the end of the code
	
	2.Function form
		Encapsulate the import sentence into the function and wait for all names to be loaded before calling.
		The principle is to change the order, but in different ways.

7. Import sequence of modules

  1. Find in memory
  2. Find in built-in module
  3. Sys.path (custom module) found in system path
    If none is found, an error is reported
# Note: try not to conflict with built-in modules when naming py files.
import sys
print(sys.path)
# The first element in the result is always the path of the current execution file.

# When a custom module cannot be found
 Mode 1:
	Add the module yourself to the sys.path in
	sys.path.append('The path of the module')

Mode 2:
	from...import...Sentence pattern
	from Folder name.Folder name...import Module name
	from Folder name.Module name...import name

8. Absolute import and relative Import

Unfinished to be continued

Posted by uptime on Tue, 23 Nov 2021 05:50:41 -0800