Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Follow publication

Python’s Hidden Superpower: Bytecode Hacking with dis and code Modules 🚀

Elshad Karimov
Stackademic
Published in
3 min readMar 2, 2025

--

Photo by Chris Ried on Unsplash

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) → Load x into the stack
  • LOAD_FAST 1 (y) → Load y into the stack
  • BINARY_ADD → Add them
  • RETURN_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!

🔹 3. Manually Creating Python Functions…

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet

Write a response