On this page
  1. opcode
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Checking Stack Effects of Instructions
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

opcode

Prev: numbers | Up: stdlib_module | Next: operator
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — opcode
Tags: #public #python3 #stdlib


Import

import opcode

Overview

CPython bytecode instruction tables (opname, opmap, HAVE_ARGUMENT, stack_effect(), hasconst, hasname, haslocal) used internally by dis and the compiler. Use opcode alongside dis when writing bytecode analyzers, coverage tools, or peephole inspection scripts.

Quick Start

import opcode

load_const = opcode.opmap["LOAD_CONST"]
assert opcode.opname[load_const] == "LOAD_CONST"
assert opcode.stack_effect(load_const, 0) == 1

Implementation Walkthrough

1. Checking Stack Effects of Instructions

opcode.stack_effect(op, oparg=None, *, jump=None) computes the net evaluation-stack delta for an instruction—essential when validating or transforming bytecode:

import opcode

assert opcode.stack_effect(opcode.opmap["POP_TOP"]) == -1
assert opcode.stack_effect(opcode.opmap["RETURN_VALUE"]) == -1

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes