Bytecode
In Python, bytecode is a low-level set of instructions that is portable across different platforms, which means it can be executed on any machine that has a compatible CPython interpreter.
The bytecode runs in the Python virtual machine (PVM) and acts as a bridge between the high-level Python code and the machine code that the CPU executes.
The Python interpreter compiles your source code into bytecode and stores it in .pyc
files in the __pycache__/
directory when you import a module. This compiled code allows Python to load modules faster because it skips the compilation step if the bytecode is already up-to-date. Note that bytecode isn’t human-readable and is specific to the Python version that generated it.
Example
Here’s an example that lets you check the bytecode for a function. You can use the dis
module to disassemble Python bytecode into a more readable form:
>>> import dis
>>> def greet(name):
... return f"Hello, {name}!"
...
>>> dis.dis(greet)
1 0 RESUME 0
2 2 LOAD_CONST 1 ('Hello, ')
4 LOAD_FAST 0 (name)
6 FORMAT_VALUE 0
8 LOAD_CONST 2 ('!')
10 BUILD_STRING 3
12 RETURN_VALUE
This output shows the sequence of bytecode instructions that the Python interpreter executes.
Related Resources
Tutorial
CPython Internals: Paperback Now Available!
After almost two years of writing, reviewing, and testing, we're delighted to announce that CPython Internals: Your Guide to the Python 3 Interpreter is available in paperback! In this article, you'll see how the book can help you take your Python skills to the next level.