Skip to content

Instantly share code, notes, and snippets.

@duke13137
Last active December 6, 2025 06:18
Show Gist options
  • Select an option

  • Save duke13137/ad16d3f709e8cf14e2bef3c1b5e73a10 to your computer and use it in GitHub Desktop.

Select an option

Save duke13137/ad16d3f709e8cf14e2bef3c1b5e73a10 to your computer and use it in GitHub Desktop.
Python Debug Cheatsheet

Python Debug Cheatsheet

Print Object Representations

# Basic print (calls __str__)
print(obj)
print(f"result: {obj}")

# Debug representation (calls __repr__)
print(repr(obj))
print(f"{obj=}")           # Python 3.8+: prints "obj=<value>"
print(f"{obj=!r}")          # Force repr formatting

# Unknown objects
print(f"{type(obj)=} {dir(obj)=}")

# Multiple variables at once
print(f"{x=} {y=} {result=}")

Pretty Print Structures

from pprint import pprint

# Dictionaries and nested structures
pprint(data_dict)
pprint(data_dict, width=120, depth=2)

# Large lists (slice first)
pprint(big_list[:10])      # First 10 items
pprint(big_list[-5:])      # Last 5 items

# All local variables in function
pprint(locals())

# All instance variables in method
pprint(vars(self))
pprint(self.__dict__)      # Alternative

Assertion Debugging

  • most useful for big loops and deep recursive algorithms
  • print stack trace (how does code get here?)
# Validate loop invariants
for i, node in enumerate(graph):
    assert i < 1000, f"infinite loop? {i=} {node=}"
    assert node in visited or node == start, f"bad state {visited=}"

# Check recursion depth/state
def dfs(node, depth=0):
    assert depth < 50, f"too deep! {depth=} {node=}"
    assert node is not None, f"null node at {depth=}"

# Edge cases in algorithms
assert len(queue) > 0 or found, f"empty queue but not found: {visited=}"
assert low <= high, f"binary search bounds crossed: {low=} {high=} {target=}"

# Side-effect assertions (runs pprint if condition fails)
assert result > 0 or pprint(vars()), f"unexpected result: {result=}"
assert valid or pprint(vars(self)), f"invalid state"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment