SoFunction
Updated on 2024-11-19

The creation and role of the __pycache__ folder in pyhton explained in detail

I wrote a project in python, but after running it for the first time, I found that a __pycache__ folder was created in the root directory of the project, containing various files with the same name as the py file ending in . cpython -35 means, cpython stands for the Python interpreter implemented in the c language, and -35 stands for version 3.5. As for pyc, you need to understand the module calls first.

Module calls

When Python imports a module, it actually executes the module being imported. For example, the call module:

def haha():
  print("haha")

haha()

Main program:

import test

print("good")

Implementation results:

haha
good

How can I just simply call and not execute the called module's code? To have the called module code not be executed, you can use __name__. If there is no module import involved, the value of __name__ is __main__, and if the module is referenced by the import, then the value of __name__ within that module is the name of the file (without .py), for example:

def haha():
  print("haha")

haha()
print(__name__)

The implementation results are:

haha
__main__

If test is referenced by the import, e.g. test2:

import test

print("good")

The results of the run are:

haha
test
good

If __name__ == '__main__': is added before the executable code in the called module, the code of the called module will not be executed.

origin

Python programs run without being compiled into binary code and run the program directly from the source code. Simply put, the Python interpreter converts the source code into bytecode, and then the interpreter executes that bytecode.

Interpreter specific work:

1. Complete the loading and linking of modules;
2. Compile the source code into a PyCodeObject object (i.e., byte code) and write it into memory for the CPU to read;
3, read from memory and execute, after the end of the PyCodeObject written back to the hard disk, that is, copied to the .pyc or .pyo file to save the current directory of all the script byte code files.

After that, if the script is executed again, it first checks [whether there is a local bytecode file mentioned above] and [whether the modification time of the bytecode file is after its source file], and if it is, it will be executed directly, otherwise repeat the above steps.

The first time the code is executed, the Python interpreter has already put the compiled bytecode in the __pycache__ folder, so that if you run it again in the future, if the module being called has not been changed, then it will directly skip the compilation step and go directly to the __pycache__ folder to run the relevant *.pyc file, greatly reducing the preparation time of the project before running. This greatly reduces the preparation time before running the project.

This is the whole content of this article, I hope it will help you to learn more.