I. What Is a Python Interpreter
The Python interpreter is the core software component responsible for executing Python programs.
It is responsible not only for reading and executing Python code but also for tasks such as type management, object creation, memory management, exception handling, module loading, and runtime scheduling.
For example:
print("Hello, Python")
This code appears to contain only a function call, but the interpreter must complete a series of tasks:
- Read the Python source code.
- Analyze the lexical tokens in the code.
- Parse the syntactic structure.
- Check whether the syntax is valid.
- Compile the code into an internal representation and bytecode.
- Create or obtain runtime objects.
- Execute the corresponding operation instructions.
- Call
print()to output the content.
Therefore, the Python interpreter is not just a simple code executor but a complete language runtime environment.
1. Relationship Between the Interpreter and the Python Language
Three concepts need to be distinguished:
| Concept | Meaning |
|---|---|
| Python language | The specification that defines syntax, semantics, and language behavior |
| Python interpreter | Software that implements the ability to execute the Python language |
| Python runtime | Infrastructure such as objects, memory, exceptions, and modules provided during program execution |
The Python language itself does not require the use of any one particular interpreter implementation.
Different interpreters can use different internal architectures, as long as they implement compatible Python language behavior within the relevant scope.
2. Common Python Interpreter Implementations
Python has multiple interpreter implementations, which differ in execution approach, performance optimization, and runtime environment.
| Interpreter | Implementation | Main Features |
|---|---|---|
| CPython | C language implementation | The most mainstream Python implementation, with broad ecosystem compatibility |
| PyPy | RPython implementation | Uses JIT and other techniques to optimize execution performance |
| Jython | Java implementation | Targets the JVM environment and integrates with the Java ecosystem |
| IronPython | .NET implementation | Targets the CLR/.NET ecosystem |
| MicroPython | C language implementation | Targets microcontrollers and resource-constrained devices |
| CircuitPython | Based on MicroPython | Targets education and embedded hardware development |
Among them, CPython is currently the most common Python interpreter implementation.
The Python installation packages used in daily work, many third-party extensions, and development tools usually use CPython as their primary compatibility target.
The rest of this article mainly uses CPython as an example to explain Python's execution mechanism. Note that CPython's bytecode format, internal object structure, and specific execution details are implementation-level details, not schemes that every Python interpreter must adopt.
II. Overall Execution Flow of a Python Program
In CPython, Python source code is usually not directly converted into machine instructions that the CPU can execute. Instead, it is first compiled into Python bytecode and then executed by the interpreter.
The overall process can be summarized as follows:
flowchart TD
A["Python source code .py"] --> B["Lexical analysis"]
B --> C["Syntax analysis"]
C --> D["Abstract syntax tree AST"]
D --> E["Compilation phase"]
E --> F["Python bytecode"]
F --> G["Interpreter execution"]
G --> H["Runtime objects and memory management"]
H --> I["Program output or external operations"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
These stages are not completely independent external programs; rather, they are part of the interpreter's internal compilation and execution mechanisms.
1. Reading the Source Code
Python programs are usually saved as .py files.
For example:
name = "Alice"
age = 25
print(name, age)
The interpreter first needs to read the contents of the source file and, according to the file encoding rules, convert it into the internal text representation it uses.
Python 3 defaults to UTF-8 for source code encoding, and other compatible encodings can also be specified via an encoding declaration.
# -*- coding: utf-8 -*-
message = "你好,Python"
print(message)
Note that the encoding declaration affects how the source file is decoded; it does not mean that all strings are stored in UTF-8 when the program runs.
In Python 3, str represents Unicode text, and the specific internal storage method is determined by the implementation; encoding and decoding happen during the conversion between text and bytes.
2. Lexical Analysis
Lexical analysis is responsible for splitting the source code into the smallest meaningful lexical units, usually called tokens.
For example:
total = price * quantity
can be split into:
| Token | Type |
|---|---|
total |
Identifier |
= |
Assignment operator |
price |
Identifier |
* |
Multiplication operator |
quantity |
Identifier |
Lexical analysis mainly recognizes:
- Keywords.
- Identifiers.
- Operators.
- Literals.
- Delimiters.
- Indentation and newline-related information.
For example:
if age >= 18:
print("adult")
Here, if is a keyword, age is an identifier, >= is a comparison operator, and 18 is an integer literal.
If an invalid lexical structure appears, the interpreter will report an error at the corresponding stage.
3. Parsing
After lexical analysis produces tokens, the interpreter must also determine whether these tokens conform to Python's grammar rules.
For example:
total = 10 + 20
This is a valid assignment statement.
Whereas:
total = + * 20
does not conform to Python syntax, and the interpreter will report a SyntaxError.
Parsing builds a structural representation of the program according to Python's grammar rules.
In CPython, this stage generates an Abstract Syntax Tree (AST).
4. Abstract Syntax Tree (AST)
The AST is a tree-shaped representation of a program's syntactic structure.
It preserves the logical structure of the program but does not retain all the surface details of the source code — for example, it does not need to store spaces and comments in full.
For example:
result = 10 + 20
can be abstracted as:
Assignment node
├── Target: result
└── Value: addition expression
├── Left operand: 10
└── Right operand: 20
You can view the AST using the Python standard library:
import ast
source = "result = 10 + 20"
tree = ast.parse(source)
print(ast.dump(tree, indent=4))
The AST is very important in the following scenarios:
- Compiler analysis.
- Static code checking.
- Code formatting.
- Automatic code generation.
- Code transformation.
- IDE syntax analysis.
- Security rule checking.
For example, Ruff, some static analysis tools, and code transformation tools use syntax trees or related intermediate representations to analyze code.
5. Compilation to Bytecode
After the AST is built, CPython continues with the compilation process, converting the program into code objects, which contain Python bytecode as well as other information required for execution.
For example:
def add(a, b):
return a + b
After compilation, the function forms a corresponding code object.
You can view the bytecode using the dis module:
import dis
def add(a, b):
return a + b
dis.dis(add)
Bytecode instructions may differ between Python versions, so the instruction sequence of a particular version should not be treated as a permanently fixed language specification.
Bytecode mainly serves the interpreter's internal execution; it is not machine code that is executed directly by the CPU.
3. What Is Python Bytecode
Bytecode is an intermediate instruction representation formed after Python source code is compiled.
It is closer to the interpreter's execution model than high-level language source code, but it still needs the Python virtual machine or a corresponding runtime to execute it.
1. The Role of Bytecode
Bytecode mainly performs the following responsibilities:
- Convert high-level syntax into unified execution instructions.
- Reduce the complexity of the interpreter directly processing source code.
- Support reuse of code objects.
- Support execution of modules and functions.
- Provide a basis for interpreter optimization.
For example:
x = 10
y = 20
z = x + y
After compilation, it produces bytecode corresponding to operations such as loading constants, storing variables, and performing addition.
You can use dis to inspect it:
import dis
def calculate():
x = 10
y = 20
z = x + y
return z
dis.dis(calculate)
The output varies depending on the CPython version.
When understanding bytecode, the focus is not on memorizing each instruction, but on understanding what operation an instruction describes and how the interpreter executes these operations.
2. Differences Between Bytecode and Machine Code
| Comparison Dimension | Python Bytecode | Machine Code |
|---|---|---|
| Target | Python virtual machine | CPU |
| Executor | Python interpreter | Processor |
| Instruction system | Defined by the Python implementation | CPU instruction set architecture |
| Hardware dependency | Usually low | Related to the target CPU architecture |
| Direct execution | Cannot be directly executed by an ordinary CPU | Can be executed by the corresponding CPU |
| Main role | Describes Python operations | Describes processor operations |
For example:
x = 1 + 2
Python bytecode can express operations such as loading constants, performing calculations, and saving results.
CPU machine code, on the other hand, corresponds to actual instructions under a specific processor architecture.
The two exist at different levels of abstraction.
3. Bytecode and .pyc Files
Python can cache the bytecode compiled from a module in a .pyc file.
For example:
project/
├── main.py
├── utils.py
└── __pycache__/
└── utils.cpython-314.pyc
.pyc files are usually stored in the __pycache__ directory, and the file name may contain the Python implementation and version identifier.
Its main purpose is to reduce compilation overhead when a module is imported repeatedly.
Note that:
.pycis a bytecode cache, not a standalone native executable file..pycis usually related to a specific Python implementation and version.- The bytecode format may change with Python versions.
.pycis not guaranteed to be compatible across different versions.- Deleting
.pycusually does not affect program operation; the interpreter can regenerate the cache.
4. How Are .pyc Files Generated?
When a module is imported, CPython can check whether a valid bytecode cache exists.
If the cache is valid, the code object in the cache can be loaded directly; if the cache does not exist or has become invalid, the source code is recompiled.
flowchart TD
A["Import Python module"] --> B{"Does .pyc cache exist?"}
B -->|No| C["Read .py source file"]
B -->|Yes| D{"Is cache valid?"}
D -->|Yes| E["Load bytecode cache"]
D -->|No| C
C --> F["Compile and generate code object"]
F --> G["Write .pyc according to cache policy"]
G --> H["Execute module code"]
E --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
CPython determines whether a .pyc is valid according to the cache policy.
Common policies include:
- Timestamp mode: determined based on information such as the source file timestamp and file size.
- Hash mode: determined based on the hash value of the source file content.
You can use the following command to view Python's cache tag:
import sys
print(sys.implementation.cache_tag)
Note that __pycache__ is mainly used for module bytecode caching; it does not mean that a .pyc file must be generated every time a Python program runs. When executing a script directly, using the interactive interpreter, or running in other ways, the actual caching behavior may differ.
IV. The Python Virtual Machine (PVM)
The Python Virtual Machine (PVM) is the core execution environment in which the Python interpreter executes bytecode.
In CPython, the virtual machine is primarily responsible for interpreting and executing the bytecode instructions within code objects.
You can think of it as an abstract execution layer that runs on top of the operating system and CPU.
1. Basic responsibilities of the PVM
The Python virtual machine is primarily responsible for:
- Fetching the bytecode that needs to be executed at the moment.
- Decoding and identifying instructions.
- Performing the corresponding operations.
- Managing the execution context.
- Handling function calls and returns.
- Handling exceptions and control flow.
- Interacting with the Python object system.
For example:
def calculate(a, b):
result = a + b
return result
value = calculate(10, 20)
The virtual machine needs to handle:
- The function call.
- Parameter binding.
- Local variable management.
- The addition operation.
- Passing the return value.
- Restoring the caller's execution state.
These operations are not carried out directly through the Python source code; rather, they are accomplished jointly by the code object and the runtime execution mechanism.
2. Stack-based execution model
CPython's bytecode execution model uses stack-based operations as an important foundation.
The operand stack is used to temporarily hold intermediate data during instruction execution.
For example, suppose we have the following expression:
result = 10 + 20
Conceptually, this can be understood as:
Load constant 10
↓
Operand stack: [10]
Load constant 20
↓
Operand stack: [10, 20]
Perform addition
↓
Operand stack: [30]
Store result
↓
result = 30
What is shown here is an abstract process meant to aid understanding, not the complete bytecode instruction sequence of any particular Python version.
The stack-based execution model has the following characteristics:
- Instructions generally do not need to explicitly specify a large number of operand registers.
- Intermediate results can be passed through the operand stack.
- Function execution can use an independent execution state.
- The instruction interpreter can organize its execution logic around stack operations.
It should be noted that the internal implementation of modern CPython has undergone many optimizations, and the actual execution process should not be simply understood as every instruction strictly performing one independent push and pop operation.
3. Code objects and execution frames
When Python executes code, in addition to bytecode, it also needs to record where the program has currently reached in execution, as well as information such as local variables and exception state.
This kind of execution state is closely related to the execution frame (Frame).
In CPython, the code object (Code Object) holds the compiled code information, while the execution frame carries the context during code execution.
A code object typically contains:
- Bytecode.
- Constants.
- Variable names.
- Local variable information.
- Parameter information.
- Source code position mapping.
- Exception-handling-related information.
You can inspect a function's code object via __code__:
def add(a, b):
return a + b
code = add.__code__
print(code.co_name)
print(code.co_varnames)
print(code.co_argcount)
print(code.co_consts)
Here:
| Attribute | Meaning |
|---|---|
co_name |
Name of the code object |
co_varnames |
Names of local variables |
co_argcount |
Number of positional parameters |
co_consts |
Collection of constants |
co_names |
Names used |
co_code |
Bytecode data |
The code object itself does not contain all the runtime variable values of a particular call.
For example, the same function can be called multiple times, and each call has its own execution context.
4. Function calls and execution frames
Consider the following code:
def square(number):
result = number * number
return result
def calculate():
value = square(5)
return value
print(calculate())
When the program runs, function calls and execution state switches occur.
The conceptual flow is as follows:
flowchart TD
A["Execute module code"] --> B["Call calculate"]
B --> C["Create or enter the calculate execution frame"]
C --> D["Call square"]
D --> E["Enter the square execution frame"]
E --> F["Compute number * number"]
F --> G["Return result 25"]
G --> H["Resume calculate execution"]
H --> I["Return value"]
I --> J["Module code continues execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There are a few concepts to understand here:
- A function definition creates a function object.
- A function object is associated with a code object.
- A function call establishes a corresponding execution context.
- After the function returns, the caller continues execution.
- An execution frame and a code object are not the same concept.
Modern CPython has made many internal optimizations to execution frames and the calling process, and the way frame objects are actually created and materialized may differ from earlier versions.
V. Python's Runtime Object Model
Python organizes data in programs using an object model.
Integers, strings, lists, functions, classes, modules, and so on can all be treated as objects.
For example:
number = 100
message = "Hello"
items = [1, 2, 3]
print(type(number))
print(type(message))
print(type(items))
These objects have attributes such as type, identity, and value.
1. Everything Is an Object
In Python, ordinary data as well as functions, classes, and so on all follow the object model.
For example:
def greet():
print("Hello")
print(type(greet))
print(callable(greet))
Functions themselves are also objects, and they can be:
- Assigned to variables.
- Passed as arguments.
- Returned as return values.
- Stored in lists or dictionaries.
- Have attributes added dynamically.
Classes are likewise objects; they can be dynamically created, passed around, and operated on.
class User:
pass
user_class = User
user = user_class()
print(type(user))
This unified object model provides the foundation for Python's dynamic features and metaprogramming capabilities.
2. Name Binding and Object References
Python variables are not fixed-type memory containers in the traditional sense; rather, they are bindings between names and objects.
For example:
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
Output:
[1, 2, 3, 4]
[1, 2, 3, 4]
This is because a and b both reference the same list object.
You can use id() to inspect an object's identity:
a = [1, 2, 3]
b = a
print(id(a))
print(id(b))
print(a is b)
is is used to determine whether two names reference the same object, while == is generally used to compare object values.
3. Object Types and Type Information
Every Python object has a corresponding type.
For example:
value = 100
print(type(value))
print(isinstance(value, int))
An object's type determines which operations it supports and how those operations are performed.
For example:
number = 10
text = "Python"
print(number + 5)
print(text + " Runtime")
Although the two addition expressions use the same operator, their actual behavior is determined by the object types and their operation rules.
Python handles operations on objects of different types through mechanisms such as dynamic dispatch.
VI. Python Memory Management Mechanism
The Python interpreter is responsible not only for executing code but also for managing object creation, references, and destruction.
Taking CPython as an example, memory management mainly involves reference counting, cyclic garbage collection, and memory allocators.
1. Object Creation
For example:
user = {
"name": "Alice",
"age": 25
}
When this code runs, the interpreter needs to:
- Create a dictionary object.
- Create or obtain the corresponding key and value objects.
- Write the key-value relationships into the dictionary.
- Bind the name
userto the dictionary object.
It should be noted that object creation does not necessarily mean that brand-new underlying memory is allocated every time.
Some objects may come from caches or memory reuse mechanisms; the specific behavior depends on the object type and interpreter implementation.
2. Reference Counting
CPython uses reference counting to track how objects are referenced.
When an object is held by a new reference, its reference count usually increases; when a reference is removed, its reference count usually decreases.
When an object is no longer referenced, CPython can usually reclaim it promptly.
For example:
import sys
data = [1, 2, 3]
print(sys.getrefcount(data))
other = data
print(sys.getrefcount(data))
Here, sys.getrefcount() itself temporarily increases the object's reference count, so the output is usually a bit higher than the number of references one might intuitively expect.
Reference counting has the following characteristics:
- It can promptly identify large numbers of unreachable objects.
- Object release usually does not need to wait for a complete garbage collection cycle.
- Changes in reference relationships incur some management overhead.
- It cannot solve the circular reference problem on its own.
3. Cyclic Garbage Collection
Reference counting cannot directly handle all circular references.
For example:
class Node:
pass
a = Node()
b = Node()
a.other = b
b.other = a
del a
del b
The two objects reference each other. Even if no external variables reference them anymore, the reference counts between them may still be nonzero.
CPython's cyclic garbage collection mechanism can identify some unreachable reference cycles and reclaim the objects involved.
You can use the gc module to inspect and control garbage collection behavior:
import gc
print(gc.isenabled())
gc.collect()
It should be noted that gc.collect() requests garbage collection, but not all objects are managed by the cyclic garbage collector. The prompt release of ordinary objects mainly relies on CPython's reference counting mechanism.
4. Memory Allocator
Frequently requesting and releasing small blocks of memory directly from the operating system incurs significant overhead.
CPython therefore implements its own memory management layer.
Conceptually, it can be divided into:
flowchart TD
A["Python Object Creation Request"] --> B["Python Memory Management Interface"]
B --> C{"Memory Allocation Type"}
C -->|Small block memory| D["Allocation mechanisms such as pymalloc"]
C -->|Larger memory| E["Underlying memory allocator"]
D --> F["Memory block management"]
E --> G["System allocation interface"]
F --> H["Object uses memory"]
G --> H
H --> I["Object release or memory reuse"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
CPython's memory allocator adopts different management strategies depending on the request size and specific configuration.
Note the following:
- Releasing a Python object does not mean the memory occupied by the process will immediately decrease.
- The interpreter may retain released memory for later reuse.
- The process memory usage seen by the operating system does not necessarily decrease in sync with the number of objects.
- Different Python implementations may have different memory management strategies.
VII. Module Import and Execution Mechanism
Python programs are usually composed of multiple modules.
The module system is responsible for finding, loading, initializing, and caching modules.
For example:
import math
print(math.sqrt(16))
When the interpreter executes import math, it needs to locate the corresponding module and load it into the current runtime environment.
1. Module search path
Python looks for modules through the module search path.
You can view it with the following code:
import sys
for path in sys.path:
print(path)
Common search locations include: