Python Bytecode Generator and Modifier

0.17.0 · active · verified Sun Mar 29

The `bytecode` library is a Python module designed to generate, analyze, and modify Python bytecode. It provides an abstract representation of bytecode that can be manipulated and then converted back into executable code objects. Currently at version 0.17.0, it is actively maintained with a regular release cadence, often introducing support for new Python versions and associated bytecode changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple `Bytecode` object using `Instr` instances, convert it to a standard Python code object, and then execute it to print 'Hello World!'.

from bytecode import Instr, Bytecode

# Create bytecode for print('Hello World!')
bytecode_obj = Bytecode([
    Instr('LOAD_GLOBAL', (True, 'print')), # Load the global 'print' function
    Instr('LOAD_CONST', 'Hello World!'), # Load the string 'Hello World!'
    Instr('CALL', 1), # Call 'print' with 1 argument
    Instr('POP_TOP'), # Pop the return value (None) from the stack
    Instr('LOAD_CONST', None), # Load None
    Instr('RETURN_VALUE') # Return None
])

# Convert the bytecode object to a CPython code object
code = bytecode_obj.to_code()

# Execute the generated code
exec(code)

view raw JSON →