In my system I have created a Python application that is composed by more than one file. The directory structure of the application is the following:
application_directory
|- file_a.py
|- file_b.py
|- file_c.py
Inside the script file_c.py
are present the following imports:
import file_a
from file_b import ClassB
When I execute the script file_c.py
by the command line:
python3 file_c.py
in the folder application_folder
is created a directory called __pycache__
and inside it I find two files containing the Python bytecode and called:
__pycache__/file_a.cpython-310.pyc
__pycache__/file_b.cpython-310.pyc
Note: I have read this link and this other link to get information about the concepts of compilation in Python, bytecode, and Python interpreter as virtual machine.
To understand why are created this files I have search a lot and I have found many links about this topic. The most clear could be this answer that seems perfect to understand what happens in my context.
In the answer is present the following sentence:
Running a script is not considered an import and no .pyc will be created.
So I am asking: only for modules imported are created a file with bytecode? Why is there this difference in the management of imported modules respect to not imported scripts?
EDIT
I have found this other answer very useful to better understand how works CPython, the concept of bytecode and the file .pyc
saved to the hard disk.
All Python files are compiled to bytecode before being executed, Python just does not write the bytecode to a file.
When a module is imported from an other file, it is compiled and then cached, to make subsequent runs faster.