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)
3 RESUME 0
4 LOAD_CONST 0 ('Hello, ')
LOAD_FAST_BORROW 0 (name)
FORMAT_SIMPLE
LOAD_CONST 1 ('!')
BUILD_STRING 3
RETURN_VALUE
This output shows the sequence of bytecode instructions that the Python interpreter executes. Note that bytecode output varies between Python versions, so your output may differ.
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.