How to Disassemble Python Bytecode | Easiest Method
Before getting into the code, let me give you a quick basic background understanding about compiling python file. It is required to understand, How to Disassemble Python Bytecode.
What does actually happen when you compile the Python file?
Whenever you run the python code “python <python_file>”, it gets converted into the bytecode. CPython is an interpreter that compiles the source code into the byte-code.
The bytecode gets cached into the .pyc and .pyo file. You can check the .pyc file getting created in the same directory where your python program persists.
When you run python code next time, it runs the bytecode from the .pyc file. It saves the time by avoiding recompilation from source code to bytecode. So the execution will be faster.
Related Read: How to Compiler Python File without Executing it?
Note: It is not necessary same bytecode will work on different virtual machines.
Now back to our original question.
How to Disassemble Python Bytecode To Analyze?
There is a Python module called “dis“. This Python module is to analyze the CPython bytecode by dissembling it.
You don’t need to install dis module externally as it comes with Python by default.
The dis.dis() function Disassembles the byte source object.
Here, the byte source object can be anything like module, class, method, or code object.
Python Program to disassemble byte source (function):
Below is python program to disassemble the user-written function.
import dis def squareOfNumner(n): return n*n squareOfNumner(10) dis.dis(squareOfNumner)
The output of a program:
Note: Here, ‘4’ is a line number of the last line where the byte source code ends.
This output is more about understanding python bytecode. This makes the bytecode easily readable by the end user. It is the complete replica of the Python code.
The behavior of the dis.dis() function is different for the different byte-source object.
- For a class, it disassembles the all the methods within the class.
- If we don’t provide any byte-source object, it disassembles the last trackback.
- For a module, it disassembles all function within the module.
You can try all above byte-source objects and see the difference.
There are also some other Python functions in dis module. You can read more about it.
To learn more about compiler and interpreter, here is the difference between them. Explained in detail.