The import operation in Python is somewhat similar to # include in the C language, but it is quite different. In the C language, #include是编译前将另一个文件包含进当前文件中. Importing in Python is not just inserting one file text into another file.
Import is actually a run-time operation, and the first time the program is imported, it performs three steps.
1 Module Files found
2 compile into a bit code when needed
3 executing the code of the module to create the object it defines
These three steps are only executed when the module is imported for the first time, and then when the same module is imported, the three steps are skipped, and only the module objects loaded in memory are extracted.
Python stores the loaded modules in a table named Sys.modules, which is checked when the module is imported, and does not start the three steps above if the module exists in the table.
The module file referenced after the import statement has no file path and no file suffix. How did Python find the module and import it into the file?
The original python has a sys.path system variable that stores the search path to the import statement. This search path consists mainly of four parts:
1 Program's Home directory
2 Pythonpath Directory
3 Standard link library catalog
4 contents of any. pth file
The suffix of the import file is intentionally omitted from the import statement. Python selects the first file in the search path that matches the import file name.
In addition, the import can also use the hook program to let import when importing files to do a variety of useful things. The specific hook function is the built-in __import__ function, see the relevant manual for specific usage.
Import in Python