About the principle of Python's import mechanism

  Many people have used python and added import module_name in front of the script without thinking, but I am afraid not many people really understand the principle and mechanism of import. This article sorts out the import mechanism of Python. On the one hand, I summarize and learn it myself, and on the other hand, it helps everyone communicate.

  First explain the basic concepts:

  Module (module): In fact, it is a py file that defines various variables, functions, and classes.

  In addition to built-in modules (you can use dir(__builtins__) to see what built-in functions are available), modules are non-built-in modules. This part of the module needs to be imported with import. Non-built-in modules often need to follow third-party libraries. Generally, third-party modules are located in the "installation path\Python\Python35\Lib\site-packages" directory.

  Package (package): A hierarchical file directory, which contains modules and some sub-packages, requires a __init__.py file in the package.

  Import method:

  import module_name

  from module_name import module_element

  It is not difficult to understand that this process loads the entire contents of the module_name.py file into memory, and assigns the variable type 'module' to the variable of the same name in the current module.

  when importing the module. The folder where the module is located will automatically generate a corresponding __pycache__\module_name.cpython-36.pyc file

 

  How to load? - Loading method and usage

  Way:

  1.import package

  Read the __init__.py of this package, that is to say, the essence of the imported package is to execute the __init__.py file under the package. After the execution, a "__pycache__ / __init__.cpython-36.pyc" file will be generated in the directory of the package name. .

  2.import module

  Read the content of the entire module

  3.import package1.package2.package3.module4

  package reads __init__.py, module reads the entire module content, in order

  Note: Because the package reads __init__.py, it must be called when there is a reference in __init__.py, otherwise an error will be reported.

  where to load from?

  For python, all modules loaded into memory are placed in sys.modules, so when import is executed, it will first go to the list to check whether it has been added. If it's already in sys.modules, it's as simple as adding the name of the module to the local space where we're calling the module. If it has not been placed in sys.modules, you need to search for the files of the module in order in the directories of all paths in sys.path. These files are generally suffixed with ".py", ".pyo", ".pyc", ".pyd", ".dll", after finding these modules, you can add these modules to sys.modules, and then import the module name to the local.

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325978901&siteId=291194637