One article has a thorough understanding of Python module. Those who can't have a thorough understanding should look at their teeth

Keywords: Python Back-end

 

1. Module introduction

1.1 what is a module

When writing a long program, it is recommended to use a text editor instead of an interpreter to execute the input in the file, which is writing   script  . As the program gets longer and longer, in order to facilitate maintenance, it is best to split the script into multiple files. Another advantage of scripting is that when different programs call the same function, they don't have to copy the function to each program every time. To meet these requirements, Python stores various definitions in a file and uses them in interactive instances of scripts or interpreters. This file is   modular

A module is a combination of a series of functions.

1.2 why use modules

The maintainability of the code is improved without repeated creation   wheel   Improve development efficiency

1.3 various types of modules

python
pip

1.4 representation of modules

  • The code written in python (. py file) is a python file written at ordinary times

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

  • 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 (this file may not be available in Python 3)

  • Built in modules written in C and linked to the python interpreter

2. import sentence

Keywords used by import module   import   plus   py   File name, do not add  . py  .

Example:

# Import built-in modules
>>> import time
>>> time.time()  # Direct use
1637651203.9467623
#Import custom
# Code file: foo.py 
name = 'Hans'

def hello(name):
    print("Hello, %s" % name)

# Import    
>>> import foo
>>> foo.
foo.hello(  foo.name    
>>> foo.name
'Hans'
>>> foo.hello(foo.name)
Hello, Hans
>>> foo.hello("Jack")  
Hello, Jack
          
# Multiple imports of the same module
# Code file: boo.py
print("hello")

# Import        
>>> import boo  # The first import will execute the code inside.
hello
>>> import boo		# The second import will not be executed
>>> import boo		# The second import will not be executed
>>> import boo		# The second import will not be executed
# Importing the same module multiple times will only be executed once

What happened when the module was first imported? (to import)   boo.py   Import in   foo.py   (for example)

# foo.py
name = 'Hans'

def hello(name):
    print("Hello, %s" % name)

# boo.py 
import foo
print("hello world")

foo.name
foo.hello(foo.name)
foo.hello("Jack")

# Execution results:
hello world
Hello, Hans
Hello, Jack
  1. Run import file(   boo.py  ) The global namespace that generated the file
  2. function   foo.py
  3. produce   foo.py   Global namespace run   foo.py   All the names generated by the code in the file will be archived in   foo.py   Namespace
  4. Generates an error in the imported file namespace   foo   Your name points to   foo.py   Global namespace

import   After the method is imported into the module, all variable names or function names in the module can be used, and there will be no conflict, because the variable or function in which package to use has been specified when calling

3. from...import

from...import...   The sentence pattern refers to which module or function is imported from which package or module.

Example:

# foo.py Code:
name = 'Hans'

def hello(name):
    print("Hello, %s" % name)

def hi():
    print("Hi, world")
    
# boo.py Code:    
from foo import hi  #In boo, only the hi function of foo is used
print("hello world")

hi()

# Execution results:
hello world
Hi, world

# Code boo.py 
from foo import hi
from foo import hi
from foo import hi
 Execution results:
from foo
# from...import... Multiple imports will only import once

use   from...import...   Import:

  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. Archive all the names generated after execution in the module in the module namespace
  4. There is one in the executable   hi   Execute in module namespace   hi   Value pointed to

Import

# foo.py code
print("from foo")
name = 'Hans'

def hello(name):
    print("Hello, %s" % name)

def hi():
    print("Hi, world")

# boo.py code
    
from foo import hi
print("hello world")

def hi():
    print("from boo hi")

hi()
# Execution results:
from foo
hello world
from boo hi   # It is found that the result of executing hi() is that the function in boo.py is not imported from foo.py

from...import...   Import a name specified

When using, you can write the name directly, but when the current namespace has the same name, there will be a conflict, and the used will become the current namespace

4. Extension of import method

4.1 using aliases

# Import import
>>> import foo as f  # If you define foo as f, you can only call f. if you call foo again, an error will be reported, saying that foo is not defined
>>> f.name
'Hans'

# From... Import
>>> from foo import hi as h		# Define hi as alias h, and use h directly when calling. Similarly, hi cannot be used
>>> h()
Hi, world

4.2 continuous import

# Import import
>>> import sys
>>> import os
# The above import method can be written as follows:
>>> import sys, os  # This method has the same function as the above method

# From... Import
>>> from foo import hello
>>> from foo import hi
# The above import method can be written as follows:
>>> from foo import hello, hi  # This method has the same function as the above method

import   When multiple modules are imported continuously, it is recommended if multiple modules have similar functions or belong to the same series.

If the functions are different and do not belong to a series, branch import is recommended

4.3 general import

If used from ... import ...When importing all functions in a module, the most basic method is to import them in turn
>>> from foo import hello, hi, name 
# or
>>> from foo import hello
>>> from foo import hi
>>> from foo import name 

#You can use the * sign to import all functions in a module
>>> from foo import * 


# If there are three functions in a module, you can use _all when using from... Import... And you want people to use two of them__
# code:
print("from foo")
name = 'Hans'

def hello(name):
    print("from foo. Hello, %s" % name)

def hi():
    print("from foo Hi")

def play():
    print("from foo play")

__all__ = ['hi', 'play']  # In the imported module file, you can use _ all to specify the name that can be imported

# Execution:
>>> from foo import *
from foo
>>> hi()
from foo Hi
>>> play()
from foo play
>>> hello("Hans")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hello' is not define

4.4 determine whether the py file is a module file or an execution file

You can use the function's own  __ name__   method

# foo.py code 
print("from foo")
name = 'Hans'

def hello(name):
    print("from foo. Hello, %s" % name)

def hi():
    print("from foo Hi")

def play():
    print("from foo play")

print("__name__: %s" % __name__)

# If:
from foo
__name__: __main__
# If foo.py is executed directly. _name_is _main__  

# If foo.py is imported as a module in another file:
# importTest.py code
import foo

#Execution results:
from foo
__name__: foo   
# If the foo.py file is imported as a module, the module name is returned

# 
# When a py file is imported as a module, it will directly execute all the code in the PY file. You can use _name _tojudge whether it is imported as a module. If so, it will not be executed
# Code foo.py
def hello(name):
    print("from foo. Hello, %s" % name)

def hi():
    print("from foo Hi")

def play():
    print("from foo play")

if __name__ == '__main__':
    print("from foo")
    name = 'Hans'
# Code importTest.py 
import foo
# Execution results:

#Before importing, it will be printed directly: from foo

5. Module import sequence

Order of module import:

  1. Look in memory first
  2. Then go to the built-in module
  3. Finally, go to sys.path to find the system path (user-defined module)

If none is found, an error is reported

# 1. Find in memory
# foo.py Code:

def hello(name):
    print("from foo. Hello, %s" % name)

def hi():
    print("from foo Hi")

def play():
    print("from foo play")

if __name__ == '__main__':
    print("from foo")
    name = 'Hans'
# importTest.py Code:

from foo import hello
import time 
print("Hello")
time.sleep(10)
hello("time")

# Execution results:
Hello
				#Delete foo.py at time.sleep(10). At this time, foo.py has been loaded into memory, so the following is still executed
from foo. Hello, time

#If it is executed again, an error will be reported

# 2. Search in the built-in module
# You can define a module with the same name as the built-in module to see who is imported

# Write your own time.py Code:
print("time...")

# boo.py Code: 
import time
print(time)

# Execution results:   
<module 'time' (built-in)>
# It is found that time is a built-in module, so do not conflict with the built-in module name when naming the py file

# sys.path system path lookup
>>> import sys
>>> sys.path  
['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/cloud_init-17.1-py3.6.egg', '/usr/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages']

# '' is the current directory, and then find it in turn

When a user-defined module cannot be found, the solution is:

  1. Manually add the path of the module to sys.path

    # View current directory
    [root@hans_tencent_centos82 tmp]# pwd
    /tmp
    [root@hans_tencent_centos82 tmp]# python3
    >>> import foo
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'foo'
    # Prompt no foo module.
    # Find out where the foo.py module is
    [root@hans_tencent_centos82 module]# pwd
    /tmp/module
    [root@hans_tencent_centos82 module]# ls -lrt foo.py 
    -rw-r--r-- 1 root root 202 Nov 23 16:54 foo.py
    # foo.py is in the / tmp/module directory.
    # /Add tmp/module to sys.path
    >>> import sys
    >>> sys.path.append('/tmp/module')
    >>> import foo
    >>> sys.path
    ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/cloud_init-17.1-py3.6.egg', '/usr/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/tmp/module']
    # You can see that '/ tmp/module' is added to sys.path

  2. use   from...import...   Sentence pattern

    from   Folder name. Folder name   import   Module name

    from   Folder name. Module name   import   name

    # from folder name. Folder name import module name
    
    #  foo.py is in the / tmp/module directory.
    # The current directory is / tmp
    # Use from...import
    # Execution results:
    >>> from module import foo
    >>> foo.hi()
    from foo Hi
    
    #Currently, foo.py is under / tmp/module/test /
    [root@hans_tencent_centos82 tmp]# ls -lrt /tmp/module/test/foo.py 
    -rw-r--r-- 1 root root 202 Nov 23 16:54 /tmp/module/test/foo.py
    >>> from module.test import foo
    >>> foo.play()
    from foo play
    
    # from folder name. Module name import name
    
    #Import only one function in foo module:
    >>> from module.test.foo import play
    >>> play()
    from foo play

    6. Circular import

    Circular import is not allowed

    If it does, the general solution (i.e. knowing that there is a circular import or letting it run, make mistakes again and again):

    1. Exchange sequence
      Put the sentences imported from each other at the end of the code
    2. Function form
      Put the imported sentence into the function body code and wait for all names to be loaded before calling

     

Posted by chinni_77 on Tue, 23 Nov 2021 16:18:54 -0800