Member-only story
Python’s Hidden Superpower: Bytecode Hacking with dis
and code
Modules 🚀
Most Python developers never explore how Python actually executes their code under the hood. But if you understand Python bytecode, you can:
✅ Optimize code at the lowest level
✅ Modify Python execution at runtime
✅ Write your own mini Python interpreter
Today, we’re diving into Python’s bytecode magic using the dis
and code
modules.
If you’ve never heard of bytecode hacking, prepare to be blown away. 🤯
🔹 1. What is Python Bytecode?
Before Python executes your code, it compiles it into an intermediate representation known as bytecode.
Bytecode is a low-level set of instructions that the Python interpreter executes.
📌 Example: Let’s see the bytecode for a simple function.
import dis
def add(x, y):
return x + y
dis.dis(add)
✅ Output:
2 0 LOAD_FAST 0 (x)
2 LOAD_FAST 1 (y)
4 BINARY_ADD
6 RETURN_VALUE
💡 What’s happening here?
LOAD_FAST 0 (x)
→ Loadx
into the stackLOAD_FAST 1 (y)
→ Loady
into the stackBINARY_ADD
→ Add themRETURN_VALUE
→ Return the result
This is exactly how Python executes your code!
🔹 2. How to Modify Python Bytecode? (Runtime Hacking) 🔥
📌 Changing Function Behavior Without Changing Source Code
Python stores the bytecode of a function in func.__code__
. We can modify it on the fly!
def greet():
return "Hello, World!"
print(greet()) # Normal output: Hello, World!
# Hack the bytecode: Change RETURN_VALUE to return "Hacked!"
greet.__code__ = (lambda: "Hacked!").__code__
print(greet()) # Now prints: Hacked!
✅ We just hacked a function’s behavior at runtime!