Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Files with bytecode are really created only for imported modules?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> python3 file_c.py

in the folder application_folder is created a directory called __pycache__ and inside it two files with bytecode and called:

__pycache__/file_a.cpython-310.pyc
__pycache__/file_b.cpython-310.pyc

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?

>Solution :

All files are compiled before being executed, python just does not write them to a file. In this case, because they’re imports, modules are compiled and then cached, to make subsequent runs faster.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading