Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see the assembly code of a Python file? [closed]

Out of curiosity I would like to see the assembly instructions that correspond to the code of a .py file. Are there any trustworthy solutions you can propose?

like image 203
Controller Avatar asked Feb 28 '15 00:02

Controller


People also ask

How do you view the code of a Python file?

Double-clicking a . py script will execute the script (and may not send any useful results to the screen). To view the source you can open a . py file with IDLE (which comes with Python) or even Notepad although a more advanced text editor or IDE is recommended.

Does Python generate assembly code?

Python itself generates a intermediate code for it's virtual machine. If you want to have a look at this code, use the dis module from the Python standard library. This generates a assembly-like representation of your Python function.

What is dis DIS in Python?

Source code: Lib/dis.py. The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode. h and used by the compiler and the interpreter.


1 Answers

The dis module disassembles code objects (extracting those from functions, classes and objects with a __dict__ namespace).

This means you can use it to disassemble whole modules:

import dis

dis.dis(dis)

although this isn't nearly as interesting as you may think as most modules contain several functions and classes, leading to a lot of output.

I usually focus on smaller functions with specific aspects I am interested in; like what bytecode is generated for a chained comparison:

def f(x):
    return 1 < x ** 2 < 100

dis.dis(f)

for example.

like image 152
Martijn Pieters Avatar answered Oct 02 '22 04:10

Martijn Pieters