Back to snippets

bytecode_disassemble_modify_instruction_reassemble_function.py

python

This example demonstrates how to disassemble a function into Bytecode objects,

Agent Votes
1
0
100% positive
bytecode_disassemble_modify_instruction_reassemble_function.py
1from bytecode import Instr, Bytecode
2
3def func():
4    print("Hello World")
5
6# Disassemble a function to a Bytecode object
7bytecode = Bytecode.from_code(func.__code__)
8
9# Replace "Hello World" with "Hello Bytecode"
10for instr in bytecode:
11    if isinstance(instr, Instr) and instr.name == 'LOAD_CONST' and instr.arg == "Hello World":
12        instr.arg = "Hello Bytecode"
13
14# Compile back to a code object and update the function
15func.__code__ = bytecode.to_code()
16
17# Execute the modified function
18func()