Claude Code for opcode: Python Bytecode Opcode Constants — Claude Skills 360 Blog
Blog / AI / Claude Code for opcode: Python Bytecode Opcode Constants
AI

Claude Code for opcode: Python Bytecode Opcode Constants

Published: January 14, 2029
Read time: 5 min read
By: Claude Skills 360

Python’s opcode module exposes the CPython bytecode opcode table — the mapping between mnemonic names and their numeric byte values. import opcode. Lookup: opcode.opmap["LOAD_FAST"] → int; opcode.opname[116]"LOAD_FAST". Argument groups: opcode.hasconst, opcode.haslocal, opcode.hasfree, opcode.hasname, opcode.hasjrel, opcode.hasjabs, opcode.hascompare, opcode.hasjump — each is a list of opcode ints. Has-argument threshold: opcode.HAVE_ARGUMENT (= 90 in CPython 3.11+; opcodes ≥ this value take a 1-byte argument). Stack effect: opcode.stack_effect(op_int, arg=None) → net stack delta (positive = push, negative = pop). Comparison operators: opcode.cmp_op[i] — the string operator name for a COMPARE_OP argument. Extended args: opcode.EXTENDED_ARG is the opcode that prefixes multi-byte arguments; each EXTENDED_ARG shifts the real arg left by 8 bits. Claude Code generates bytecode analyzers, opcode frequency profilers, dead code detectors, stack depth validators, and custom Python-to-Python compilers.

CLAUDE.md for opcode

## opcode Stack
- Stdlib: import opcode, dis, types
- Lookup: opcode.opmap["LOAD_CONST"]   # name → int
-         opcode.opname[100]            # int → name
- Groups: opcode.hasconst / haslocal / hasfree / hasname
-         opcode.hasjrel / hasjabs / hascompare
- Effect: opcode.stack_effect(op, arg)  # net stack delta
- Arg?:   op >= opcode.HAVE_ARGUMENT    # True if op takes an arg
- Cmp:    opcode.cmp_op[i]             # e.g. "<", "==", "in"
- ExtArg: opcode.EXTENDED_ARG           # multi-byte arg prefix opcode

opcode Bytecode Analysis Pipeline

# app/opcodeutil.py — loader, freqs, effects, dead-code, stack validator, disassembler
from __future__ import annotations

import dis
import opcode
import types
from collections import Counter
from dataclasses import dataclass, field
from typing import Any


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic opcode info helpers
# ─────────────────────────────────────────────────────────────────────────────

def opcode_name(op: int) -> str:
    """
    Return the mnemonic name for a numeric opcode.

    Example:
        opcode_name(100)   # "LOAD_CONST"
        opcode_name(116)   # "LOAD_FAST" (varies by Python version)
    """
    return opcode.opname[op] if 0 <= op < len(opcode.opname) else f"<{op}>"


def opcode_int(name: str) -> int | None:
    """
    Return the numeric opcode for a mnemonic name, or None if unknown.

    Example:
        opcode_int("LOAD_FAST")   # 124
        opcode_int("BOGUS")       # None
    """
    return opcode.opmap.get(name)


def takes_arg(op: int) -> bool:
    """Return True if this opcode takes an inline argument."""
    return op >= opcode.HAVE_ARGUMENT


def stack_delta(op: int, arg: int | None = None) -> int:
    """
    Return the net stack depth change for opcode op with the given arg.

    Example:
        stack_delta(opcode.opmap["LOAD_CONST"])   # +1
        stack_delta(opcode.opmap["POP_TOP"])       # -1
    """
    return opcode.stack_effect(op, arg)


def classify_opcode(op: int) -> list[str]:
    """
    Return a list of classification tags for an opcode.
    Tags: 'const', 'local', 'free', 'name', 'jrel', 'jabs', 'compare', 'jump'.

    Example:
        classify_opcode(opcode.opmap["LOAD_FAST"])   # ['local']
        classify_opcode(opcode.opmap["FOR_ITER"])     # ['jrel', 'jump']
    """
    tags: list[str] = []
    if op in opcode.hasconst:   tags.append("const")
    if op in opcode.haslocal:   tags.append("local")
    if op in opcode.hasfree:    tags.append("free")
    if op in opcode.hasname:    tags.append("name")
    if op in opcode.hasjrel:    tags.append("jrel")
    if op in opcode.hasjabs:    tags.append("jabs")
    if op in opcode.hascompare: tags.append("compare")
    if hasattr(opcode, "hasjump") and op in opcode.hasjump:
        tags.append("jump")
    return tags


# ─────────────────────────────────────────────────────────────────────────────
# 2. Instruction stream decoder
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class Instruction:
    offset:    int
    op:        int
    name:      str
    arg:       int | None
    arg_repr:  str = ""
    tags:      list[str] = field(default_factory=list)
    stack_effect: int = 0


def decode_bytecode(code: types.CodeType) -> list[Instruction]:
    """
    Decode a code object into a list of Instruction records.
    Handles EXTENDED_ARG prefixes for multi-byte arguments.

    Example:
        import dis, types
        co = compile("x = 1 + 2", "<string>", "exec")
        instrs = decode_bytecode(co)
        for i in instrs:
            print(i.offset, i.name, i.arg)
    """
    instructions: list[Instruction] = []
    raw = code.co_code if hasattr(code, "co_code") else bytes(code.co_code)
    extended_arg = 0
    i = 0
    while i < len(raw):
        op = raw[i]
        if op == opcode.EXTENDED_ARG:
            arg_byte = raw[i + 1] if i + 1 < len(raw) else 0
            extended_arg = (extended_arg | arg_byte) << 8
            i += 2
            continue
        if op >= opcode.HAVE_ARGUMENT:
            arg_byte = raw[i + 1] if i + 1 < len(raw) else 0
            arg = extended_arg | arg_byte
        else:
            arg = None
        extended_arg = 0
        name = opcode.opname[op]
        # Resolve arg to human-readable repr
        arg_repr = ""
        if op in opcode.hasconst and arg is not None:
            try:
                arg_repr = repr(code.co_consts[arg])
            except IndexError:
                arg_repr = f"const[{arg}]"
        elif op in opcode.haslocal and arg is not None:
            try:
                arg_repr = code.co_varnames[arg]
            except IndexError:
                arg_repr = f"var[{arg}]"
        elif op in opcode.hasname and arg is not None:
            try:
                arg_repr = code.co_names[arg]
            except IndexError:
                arg_repr = f"name[{arg}]"
        elif op in opcode.hasfree and arg is not None:
            free_vars = (getattr(code, "co_cellvars", ()) +
                         getattr(code, "co_freevars", ()))
            try:
                arg_repr = free_vars[arg]
            except IndexError:
                arg_repr = f"free[{arg}]"
        elif op in opcode.hascompare and arg is not None:
            try:
                arg_repr = opcode.cmp_op[arg]
            except IndexError:
                arg_repr = str(arg)
        elif arg is not None:
            arg_repr = str(arg)

        try:
            effect = opcode.stack_effect(op, arg)
        except (TypeError, ValueError):
            effect = 0

        instructions.append(Instruction(
            offset=i,
            op=op,
            name=name,
            arg=arg,
            arg_repr=arg_repr,
            tags=classify_opcode(op),
            stack_effect=effect,
        ))
        i += 2
    return instructions


# ─────────────────────────────────────────────────────────────────────────────
# 3. Opcode frequency profiler
# ─────────────────────────────────────────────────────────────────────────────

def opcode_frequencies(code: types.CodeType,
                       recursive: bool = True) -> Counter[str]:
    """
    Count how many times each opcode name appears in a code object.
    If recursive=True, also counts opcodes in nested code objects
    (functions, comprehensions, classes).

    Example:
        co = compile(open("script.py").read(), "script.py", "exec")
        freq = opcode_frequencies(co)
        for name, count in freq.most_common(10):
            print(f"  {name:25s} {count}")
    """
    freq: Counter[str] = Counter()
    instrs = decode_bytecode(code)
    for instr in instrs:
        freq[instr.name] += 1
    if recursive:
        for const in code.co_consts:
            if isinstance(const, types.CodeType):
                freq.update(opcode_frequencies(const, recursive=True))
    return freq


# ─────────────────────────────────────────────────────────────────────────────
# 4. Stack depth validator
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class StackReport:
    max_depth: int
    min_depth: int
    underflows: list[int]   # offsets where depth would go negative
    ok: bool


def validate_stack_depth(code: types.CodeType) -> StackReport:
    """
    Walk the instruction stream linearly and track net stack depth.
    Flags offsets where the stack would underflow.
    Note: this is a linear (not control-flow-aware) approximation.

    Example:
        co = compile("x = [i*i for i in range(10)]", "<s>", "exec")
        report = validate_stack_depth(co)
        print(report.max_depth, report.ok)
    """
    instrs = decode_bytecode(code)
    depth = 0
    max_depth = 0
    min_depth = 0
    underflows: list[int] = []
    for instr in instrs:
        depth += instr.stack_effect
        if depth < 0:
            underflows.append(instr.offset)
        max_depth = max(max_depth, depth)
        min_depth = min(min_depth, depth)
    return StackReport(
        max_depth=max_depth,
        min_depth=min_depth,
        underflows=underflows,
        ok=len(underflows) == 0,
    )


# ─────────────────────────────────────────────────────────────────────────────
# 5. All-opcodes table printer
# ─────────────────────────────────────────────────────────────────────────────

def print_opcode_table(filter_tag: str | None = None) -> None:
    """
    Print a table of all known opcodes with their numeric value and tags.
    Pass filter_tag to narrow to e.g. 'local', 'const', 'jump'.

    Example:
        print_opcode_table()
        print_opcode_table("const")
    """
    print(f"{'Op':>4}  {'Name':30s}  {'Tags'}")
    print("-" * 60)
    for name, op in sorted(opcode.opmap.items(), key=lambda x: x[1]):
        tags = classify_opcode(op)
        if filter_tag and filter_tag not in tags:
            continue
        tag_str = ", ".join(tags) if tags else "—"
        print(f"{op:4d}  {name:30s}  {tag_str}")


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== opcode demo ===")

    # ── basic lookups ─────────────────────────────────────────────────────────
    print("\n--- basic lookups ---")
    for name in ["LOAD_CONST", "LOAD_FAST", "CALL_FUNCTION",
                 "RETURN_VALUE", "POP_TOP"]:
        op = opcode.opmap.get(name)
        if op is None:
            print(f"  {name}: not in this Python version")
            continue
        delta = stack_delta(op)
        has_arg = takes_arg(op)
        tags = classify_opcode(op)
        print(f"  {name:25s}  op={op:3d}  arg={has_arg}  "
              f"Δstack={delta:+d}  tags={tags}")

    # ── decode a simple code object ───────────────────────────────────────────
    print("\n--- decode compile('x = a + b', ...) ---")
    src = "x = a + b"
    co = compile(src, "<demo>", "exec")
    instrs = decode_bytecode(co)
    for instr in instrs:
        arg_s = f"{instr.arg_repr}" if instr.arg_repr else ""
        print(f"  {instr.offset:4d}  {instr.name:25s}  {arg_s}")

    # ── opcode frequency ──────────────────────────────────────────────────────
    print("\n--- opcode_frequencies (list comp) ---")
    co2 = compile("[x*x for x in range(100)]", "<demo>", "eval")
    freq = opcode_frequencies(co2)
    for name, count in freq.most_common(8):
        print(f"  {name:25s} {count}")

    # ── stack depth validator ─────────────────────────────────────────────────
    print("\n--- stack depth validator ---")
    co3 = compile("y = [i**2 for i in range(10) if i % 2 == 0]", "<s>", "exec")
    report = validate_stack_depth(co3)
    print(f"  max_depth={report.max_depth}  min_depth={report.min_depth}  "
          f"ok={report.ok}  underflows={report.underflows}")

    # ── compare ops ───────────────────────────────────────────────────────────
    print("\n--- cmp_op table ---")
    for i, name in enumerate(opcode.cmp_op):
        print(f"  [{i}] {name}")

    print("\n=== done ===")

For the dis stdlib alternative — dis.get_instructions(code) returns dis.Instruction named-tuples with opname, opcode, arg, argval, argrepr, offset, starts_line, and is_jump_target — use dis.get_instructions() when you need a high-level, human-readable instruction stream with jump analysis; use opcode directly when you need the raw numeric constants, stack effect computation, or opcode classification tables to build your own bytecode tools. For the bytecode (PyPI) alternative — the bytecode library provides Bytecode, ConcreteInstr, and ControlFlowGraph to read, transform, and rewrite CPython bytecode at a high level — use bytecode when you are writing a bytecode optimizer or code transformer that needs control flow graph operations; use opcode + dis for read-only analysis and introspection. The Claude Skills 360 bundle includes opcode skill sets covering opcode_name()/opcode_int()/takes_arg()/stack_delta() primitives, classify_opcode() tag classifier, Instruction dataclass + decode_bytecode() decoder, opcode_frequencies() recursive counter, validate_stack_depth()/StackReport linear validator, and print_opcode_table() filter printer. Start with the free tier to try CPython bytecode patterns and opcode pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free