Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.3 — Bytecode and the dis Module
Python · Example 2 of 3

Code objects, compile and exec

CPython compiles your source into bytecode, a list of small instructions for a stack-based virtual machine, and stores it in a code object. The dis module prints that bytecode, which shows what a line really costs and how the specialising interpreter speeds up hot code.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the opcode names of lambda x: x + 1 with dis.get_instructions.

02

Print the co_varnames and co_consts of a function that has a parameter n and a local string text.

03

Compile the expression "2 * 21" in eval mode, print its constants, and evaluate it.

Explain it without notes

01

What is bytecode, and who runs it?

02

What does a stack-based virtual machine do for the expression a * b + 1?

03

What is the specialising adaptive interpreter, and what changed in Python 3.11?

04

Why can x = 6 * 7 run no multiplication at run time?

05

Why does a try block cost almost nothing when no exception is raised, and what does that tell you about EAFP style?

Code objects, compile and exec
Sign in to run this example in your browser.

Expected output

name:         scale
arguments:    ('values', 'factor')
all locals:   ('values', 'factor', 'total', 'v')
constants:    (None, 0)
global names: ()
stack needed: True
bytecode is bytes: True
constants: (42, None)
answer: 42
has a loop opcode: True
first opcode: RESUME