0
0
PythonHow-ToBeginner · 3 min read

How to See Bytecode of Python Function Easily

To see the bytecode of a Python function, use the dis module's dis() function by passing your function as an argument. This shows the low-level instructions Python runs for that function.
📐

Syntax

Use the dis.dis() function from the dis module to display bytecode of a Python function.

  • dis.dis(function_name): Shows the bytecode instructions for function_name.
python
import dis

def example():
    return 42

dis.dis(example)
Output
3 0 LOAD_CONST 1 (42) 2 RETURN_VALUE
💻

Example

This example defines a simple function and uses dis.dis() to print its bytecode instructions. The output shows Python's low-level steps to run the function.

python
import dis

def greet(name):
    message = f"Hello, {name}!"
    return message

dis.dis(greet)
Output
3 0 LOAD_CONST 1 ('Hello, ') 2 LOAD_FAST 0 (name) 4 FORMAT_VALUE 0 6 LOAD_CONST 2 ('!') 8 BUILD_STRING 3 10 STORE_FAST 1 (message) 4 12 LOAD_FAST 1 (message) 14 RETURN_VALUE
⚠️

Common Pitfalls

One common mistake is trying to print bytecode by just printing the function object, which shows only the function's memory address, not its bytecode.

Always use dis.dis() to see bytecode.

python
def add(a, b):
    return a + b

print(add)  # Wrong: prints function info, not bytecode

import dis

dis.dis(add)  # Correct: prints bytecode
Output
<function add at 0x7f8c2c3e1d30> 2 0 LOAD_FAST 0 (a) 2 LOAD_FAST 1 (b) 4 BINARY_ADD 6 RETURN_VALUE
📊

Quick Reference

CommandDescription
dis.dis(function)Show bytecode of the given function
import disImport the disassembly module
dis.dis(code_object)Show bytecode of a code object
function.__code__Access the code object of a function

Key Takeaways

Use the dis module's dis() function to view Python function bytecode.
Passing the function name to dis.dis() prints its low-level instructions.
Printing a function directly does not show bytecode, use dis.dis() instead.
The bytecode helps understand what Python executes behind the scenes.