Function of .pyc files in Python

4

If the Python language is interpreted, why are there .pyc files that are compiled bytecodes?

    
asked by anonymous 25.05.2017 / 07:14

1 answer

6

Python, like Java, works with a virtual machine. In the case of Java, it is mandatory to send to the virtual machine only the compiled code, hence the code of .class . In Python, the virtual machine itself works with the language compiler, so it accepts pure Python code .py as well as its bytecode version .pyc .

On the question of one language being called interpreted and another being called compiled: in both cases, compilation and interpretation occurs. In the case of Java, the compilation occurs at a time prior to execution, in the call to javac to do the .java -> .class transformation. After the .class is generated, there is the interpretation of the bytecodes generated to execute the program. Can I make an analogy here with C and the processor of my x86 machine; the gcc will transform the C code into x86 machine language, so that the processor receives the binary and executes them.

In Python, the compilation process does not need to occur a priori, happening at a later time. Just like in Java and C, there is a code reading by doing grammar validation (syntax error detection) and transforming it into something easier to operationalize. The result of a successful compilation is a set of Python bytecodes equivalent to the original Python code. After this compilation process, it is passed to the bytecode interpreter to handle them, just as the JVM (Java Virtual Machine) does with the Java compiler, analogous to how the x86 processor does with the binary generated by the compilation of the file C.

To avoid going through the whole compile process again, which requires grammar validation and search for syntactic errors, once the Python code compilation has been generated, it can be stored for future use. This is done for the sake of optimization. As long as there are no changes to your original .py file, the .pyc generated will be true to the desired code, behaving as expected. When you change .py , there is the detection of this change and the Python compiler goes into the field to generate the new .pyc .

In cases where it is not possible to generate the .pyc file (for example, Python code running from a read-only file system), this optimization does not occur, so it will always compile the original code for , the interpretation and execution of its bytecodes occur.

    
25.05.2017 / 13:04