xdis: Python Cross-Version Byte-Code Disassembler

6.3.0 · active · verified Thu Apr 16

xdis is a Python library that provides a cross-version byte-code disassembler and marshal routines. It enables the inspection and manipulation of Python bytecode across a wide range of Python versions, from 1.0 up to 3.15+. The current version is 6.3.0, and it maintains an active release cadence, frequently updating with support for new Python versions and their respective bytecode changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `xdis.std.Bytecode` as a drop-in replacement for the standard library's `dis.Bytecode` to inspect a Python function's bytecode. While `xdis` excels at disassembling bytecode from *different* Python versions, this example focuses on its core disassembler functionality. For advanced cross-version loading from `.pyc` files, users should refer to `xdis.load` functions.

import marshal
import types
from xdis.std import Bytecode

def example_function():
    a = 10
    b = 'hello'
    if a > 5:
        print(b)
    return a

# Get the code object of the function
code_obj = example_function.__code__

# Disassemble using xdis.std.Bytecode (similar to stdlib dis)
print(f"\nDisassembly for Python {code_obj.co_firstlineno} via xdis.std:")
for instr in Bytecode(code_obj):
    print(instr)

# Example of loading bytecode from a marshal.dumps() output (simulated .pyc content)
# For true cross-version loading, you'd use xdis.load.load_bytecode_from_file
# or xdis.load.load_bytecode_from_cstring to specify the Python magic number.

def mock_marshal_loader(code_obj, python_version):
    # This is a simplified example; xdis.load handles actual magic numbers/versions
    # The real power is in loading *other* Python versions' bytecode.
    # For simplicity here, we'll just demonstrate disassembling a marshalled object.
    marshalled_code = marshal.dumps(code_obj)
    return marshalled_code

marshalled_bytes = mock_marshal_loader(code_obj, (3, 9)) # Simulate Python 3.9 bytecode

try:
    # To truly demonstrate xdis's cross-version capability, you'd load a .pyc file
    # generated by a *different* Python version than the one running this code.
    # For this example, we'll just show disassembling an arbitrary code object.
    # For actual cross-version loading, investigate xdis.load functions.
    print(f"\nDisassembly of a marshalled code object (Python {code_obj.co_firstlineno}):")
    # Note: For actual different Python versions, you'd need the specific magic number
    # and potentially xdis.load.load_bytecode_from_cstring or file-based loaders.
    # We'll re-disassemble the current code_obj for a runnable example.
    from xdis.bytecode import disassemble
    disassemble(code_obj)
except Exception as e:
    print(f"Could not fully demonstrate cross-version load in quickstart due to complexity: {e}")

view raw JSON →