If Python is interpreted, what are .pyc files?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Python is often described as an interpreted language, meaning that it executes instructions directly and freely without the need for prior compilation into machine-level code. However, this definition is somewhat simplistic. In reality, Python's execution involves both an interpreter and a layer of compilation, giving rise to .pyc files. Understanding this connection clarifies Python's execution process and highlights the role of .pyc files in it.
Understanding Python's Execution Model
Python's execution begins with the source code written in files with the .py extension. These files contain plain text and are easily readable by humans. Before execution, this source code undergoes several transformations:
- Lexical Analysis: The Python interpreter first tokenizes the source code into a stream of tokens, recognizing keywords, operators, identifiers, and literals.
- Parsing: Next, the stream of tokens is parsed to create an Abstract Syntax Tree (AST) that represents the grammatical structure of the source code.
- Compilation: The AST is then transformed into bytecode. This intermediate, high-level representation is designed for execution by the Python virtual machine (PVM).
- Execution: Finally, the PVM executes the bytecode to perform the programmed tasks.
The Role of .pyc Files
The compilation step is central to the creation of .pyc files. Once the bytecode is generated, Python saves it to a file with a .pyc extension, which stands for "Python compiled". Here are important points regarding .pyc files:
- Purpose:
.pycfiles speed up the start-up time of Python programs. They allow the PVM to skip the initial compilation of the source code if the.pycbytecode is already available and up to date. - Storage: Python places
.pycfiles in the__pycache__directory, named after the platform (considering factors such as Python version and architecture). For instance, a script namedexample.pymay generate__pycache__/example.cpython-38.pycfor Python 3.8. - Comparison with Source Files:
.pycfiles are a compiled form of.pyfiles but they still require the PVM to execute, as they are not machine code. They are specific to the Python version, meaning that a.pycgenerated by Python 3.8 is not usually compatible with Python 3.9. - Checking for Changes: When a script runs, Python checks for the presence and timestamp of the corresponding
.pycfile. If the source code has changed since the last compilation, or if the bytecode is missing or incompatible, Python recompiles the source code to update the.pyc.
Example: Understanding the Use of .pyc Files
Consider the simple script hello.py:
When this file is executed, Python performs the compilation and saves the bytecode in a .pyc file:
After the execution, a __pycache__ directory is created:

