mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
Every page now loads /webmcp.js, scripts/webmcp.ts with its types stripped (npm run webmcp). Where the browser has document.modelContext it registers two read-only tools: search_skills over the published skills index, and get_skill, which returns a skill's markdown checked against the index digest. The markdown alternate link moves from build.py to site.py, so CI holds every page to it. The API catalog gains the site itself (llms.txt and the skills index) and hanzo.ai/agents; the live discovery check now fetches every catalog link. tests/site.mjs drives the tools through a recording modelContext, and checks a browser without one loads clean.
785 lines
32 KiB
HTML
785 lines
32 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>debugging-python-debugging</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/debugging-python-debugging">
|
|
<link rel="alternate" type="text/markdown" href="/debugging-python-debugging.md">
|
|
<script type="module" src="/webmcp.js"></script>
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/debugging-python-debugging.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>debugging-python-debugging</h1><p class="lede">Comprehensive guide to Python debugging tools and techniques. Covers pdb (built-in debugger), ipdb (IPython integration), VSCode debugger, PyCharm debugger, pytest debugging, remote debugging with debugpy, and performance profiling with cProfile.</p><h1>Python Debugging</h1>
|
|
<p><strong>Last Updated</strong>: 2025-10-26</p>
|
|
<h2>Overview</h2>
|
|
<p>Python provides multiple debugging tools from built-in pdb to IDE-integrated debuggers. This guide covers the full debugging toolkit for Python development.</p>
|
|
<h2>Core Debugging Tools</h2>
|
|
<h3>Tool Comparison</h3>
|
|
<p>| Tool | Use Case | Pros | Cons | |------|----------|------|------| | pdb | Built-in CLI debugger | No dependencies, always available | Basic interface | | ipdb | Enhanced pdb | IPython features, tab completion | Requires ipdb package | | VSCode | GUI debugging | Visual, breakpoints, watch | Requires VSCode | | PyCharm | Full-featured IDE | Best GUI debugger | Heavy IDE | | pytest --pdb | Test debugging | Drops into debugger on failure | Test context only | | debugpy | Remote debugging | VSCode remote debugging | Setup required |</p>
|
|
<hr>
|
|
<h2>pdb: Built-in Debugger</h2>
|
|
<h3>Basic Usage</h3>
|
|
<p><strong>Start pdb</strong>:</p>
|
|
<pre><code class="lang-python"># Method 1: Insert breakpoint in code
|
|
import pdb; pdb.set_trace()
|
|
|
|
# Method 2: Python 3.7+ built-in breakpoint()
|
|
breakpoint()
|
|
|
|
# Method 3: Run script with pdb
|
|
python -m pdb script.py</code></pre>
|
|
<p><strong>Example</strong>:</p>
|
|
<pre><code class="lang-python">def calculate_sum(numbers):
|
|
total = 0
|
|
for num in numbers:
|
|
breakpoint() # Execution pauses here
|
|
total += num
|
|
return total
|
|
|
|
result = calculate_sum([1, 2, 3, 4, 5])</code></pre>
|
|
<h3>pdb Commands</h3>
|
|
<p><strong>Navigation</strong>:</p>
|
|
<pre><code class="lang-python"># Step into function
|
|
(Pdb) s
|
|
(Pdb) step
|
|
|
|
# Step over (don't enter functions)
|
|
(Pdb) n
|
|
(Pdb) next
|
|
|
|
# Continue until return
|
|
(Pdb) r
|
|
(Pdb) return
|
|
|
|
# Continue execution
|
|
(Pdb) c
|
|
(Pdb) continue
|
|
|
|
# Quit debugger
|
|
(Pdb) q
|
|
(Pdb) quit</code></pre>
|
|
<p><strong>Inspection</strong>:</p>
|
|
<pre><code class="lang-python"># Print expression
|
|
(Pdb) p variable_name
|
|
(Pdb) p len(my_list)
|
|
|
|
# Pretty-print
|
|
(Pdb) pp my_dict
|
|
|
|
# List source code
|
|
(Pdb) l
|
|
(Pdb) list
|
|
|
|
# List specific lines
|
|
(Pdb) l 10, 20
|
|
|
|
# Long list (11 lines)
|
|
(Pdb) ll
|
|
|
|
# Show current location
|
|
(Pdb) w
|
|
(Pdb) where
|
|
|
|
# Show call stack
|
|
(Pdb) bt
|
|
(Pdb) backtrace</code></pre>
|
|
<p><strong>Breakpoints</strong>:</p>
|
|
<pre><code class="lang-python"># Set breakpoint at line
|
|
(Pdb) b 42
|
|
(Pdb) break script.py:42
|
|
|
|
# Set breakpoint at function
|
|
(Pdb) b function_name
|
|
|
|
# Conditional breakpoint
|
|
(Pdb) b script.py:42, count > 10
|
|
|
|
# List breakpoints
|
|
(Pdb) bl
|
|
(Pdb) break
|
|
|
|
# Clear breakpoint
|
|
(Pdb) cl 1
|
|
(Pdb) clear 1
|
|
|
|
# Disable/enable breakpoint
|
|
(Pdb) disable 1
|
|
(Pdb) enable 1</code></pre>
|
|
<p><strong>Advanced</strong>:</p>
|
|
<pre><code class="lang-python"># Execute Python code
|
|
(Pdb) !variable = 42
|
|
(Pdb) !print(f"Debug: {count}")
|
|
|
|
# Run until line
|
|
(Pdb) unt 50
|
|
(Pdb) until 50
|
|
|
|
# Jump to line (dangerous!)
|
|
(Pdb) j 50
|
|
(Pdb) jump 50
|
|
|
|
# Display expression every step
|
|
(Pdb) display count
|
|
|
|
# Run commands on breakpoint hit
|
|
(Pdb) commands 1
|
|
(com) print(f"Count: {count}")
|
|
(com) continue
|
|
(com) end</code></pre>
|
|
<h3>Post-Mortem Debugging</h3>
|
|
<p><strong>Debug after exception</strong>:</p>
|
|
<pre><code class="lang-python">import pdb
|
|
|
|
def buggy_function():
|
|
x = 1
|
|
y = 0
|
|
z = x / y # ZeroDivisionError
|
|
|
|
try:
|
|
buggy_function()
|
|
except:
|
|
pdb.post_mortem() # Drops into debugger at exception</code></pre>
|
|
<p><strong>Automatic post-mortem</strong>:</p>
|
|
<pre><code class="lang-bash"># Run with automatic post-mortem
|
|
python -m pdb -c continue script.py</code></pre>
|
|
<hr>
|
|
<h2>ipdb: Enhanced Debugger</h2>
|
|
<h3>Installation & Setup</h3>
|
|
<pre><code class="lang-bash"># Install via uv (recommended)
|
|
uv add --dev ipdb
|
|
|
|
# Or pip
|
|
pip install ipdb</code></pre>
|
|
<h3>ipdb Features</h3>
|
|
<p><strong>Tab completion, syntax highlighting, history</strong>:</p>
|
|
<pre><code class="lang-python">import ipdb; ipdb.set_trace()
|
|
|
|
# Or use breakpoint with PYTHONBREAKPOINT
|
|
export PYTHONBREAKPOINT=ipdb.set_trace</code></pre>
|
|
<p><strong>IPython features in debugger</strong>:</p>
|
|
<pre><code class="lang-python">(ipdb) ?variable_name # Show docstring
|
|
(ipdb) ??function_name # Show source code
|
|
(ipdb) %timeit expression # Benchmark expression
|
|
(ipdb) %debug # Enhanced debugging</code></pre>
|
|
<p><strong>Auto-completion</strong>:</p>
|
|
<pre><code class="lang-python">(ipdb) my_var.<TAB> # Shows methods/attributes
|
|
(ipdb) my_dict['ke<TAB> # Completes dictionary keys</code></pre>
|
|
<hr>
|
|
<h2>VSCode Debugger</h2>
|
|
<h3>Setup</h3>
|
|
<p><strong>install.json (launch configuration)</strong>:</p>
|
|
<pre><code class="lang-json">{
|
|
"version": "0.2.0",
|
|
"configurations": [
|
|
{
|
|
"name": "Python: Current File",
|
|
"type": "python",
|
|
"request": "launch",
|
|
"program": "${file}",
|
|
"console": "integratedTerminal",
|
|
"justMyCode": false
|
|
},
|
|
{
|
|
"name": "Python: Module",
|
|
"type": "python",
|
|
"request": "launch",
|
|
"module": "mypackage.main",
|
|
"console": "integratedTerminal"
|
|
},
|
|
{
|
|
"name": "Python: Pytest",
|
|
"type": "python",
|
|
"request": "launch",
|
|
"module": "pytest",
|
|
"args": ["tests/", "-v"],
|
|
"console": "integratedTerminal"
|
|
}
|
|
]
|
|
}</code></pre>
|
|
<h3>Debugging Workflow</h3>
|
|
<p><strong>Set breakpoints</strong>:</p>
|
|
<ol><li>Click left gutter to set breakpoint (red dot)</li><li>Right-click breakpoint → Edit Breakpoint → Add condition</li><li>F5 to start debugging</li></ol>
|
|
<p><strong>Debug controls</strong>:</p>
|
|
<pre><code>F5: Start debugging / Continue
|
|
F10: Step over
|
|
F11: Step into
|
|
Shift+F11: Step out
|
|
Ctrl+Shift+F5: Restart
|
|
Shift+F5: Stop</code></pre>
|
|
<p><strong>Debug panels</strong>:</p>
|
|
<ul><li><strong>Variables</strong>: Inspect local/global variables</li><li><strong>Watch</strong>: Add expressions to watch</li><li><strong>Call Stack</strong>: Navigate stack frames</li><li><strong>Breakpoints</strong>: Manage all breakpoints</li></ul>
|
|
<h3>Conditional Breakpoints</h3>
|
|
<p><strong>Expression condition</strong>:</p>
|
|
<pre><code class="lang-python"># Break when count > 10
|
|
count > 10
|
|
|
|
# Break when username is "admin"
|
|
username == "admin"
|
|
|
|
# Break when list is empty
|
|
len(my_list) == 0</code></pre>
|
|
<p><strong>Hit count</strong>:</p>
|
|
<pre><code># Break on 5th hit
|
|
= 5
|
|
|
|
# Break every 10 hits
|
|
% 10 == 0</code></pre>
|
|
<h3>Logpoints</h3>
|
|
<p><strong>Log without stopping</strong>:</p>
|
|
<ol><li>Right-click gutter → Add Logpoint</li><li>Message: <code>Count is {count}, Total: {total}</code></li><li>Logs to Debug Console without pausing</li></ol>
|
|
<hr>
|
|
<h2>PyCharm Debugger</h2>
|
|
<h3>Setup & Features</h3>
|
|
<p><strong>Start debugging</strong>:</p>
|
|
<ol><li>Set breakpoints (click gutter)</li><li>Right-click script → Debug 'script.py'</li><li>Or: Run → Debug...</li></ol>
|
|
<p><strong>Advanced features</strong>:</p>
|
|
<ul><li><strong>Smart step into</strong>: Choose which function to step into</li><li><strong>Drop frame</strong>: Restart from previous frame</li><li><strong>Evaluate expression</strong>: Execute code in current context</li><li><strong>Watches</strong>: Persistent expression evaluation</li><li><strong>Thread frames</strong>: Multi-threaded debugging</li></ul>
|
|
<h3>Remote Debugging (PyCharm Professional)</h3>
|
|
<p><strong>Setup remote interpreter</strong>:</p>
|
|
<ol><li>Settings → Project → Python Interpreter</li><li>Add → SSH Interpreter</li><li>Configure SSH connection</li><li>Map paths: local ↔ remote</li></ol>
|
|
<p><strong>Debug remotely</strong>:</p>
|
|
<pre><code class="lang-python"># On remote machine (install pydevd-pycharm)
|
|
import pydevd_pycharm
|
|
pydevd_pycharm.settrace('localhost', port=12345, stdoutToServer=True, stderrToServer=True)</code></pre>
|
|
<hr>
|
|
<h2>pytest Debugging</h2>
|
|
<h3>pytest --pdb</h3>
|
|
<p><strong>Drop into debugger on failure</strong>:</p>
|
|
<pre><code class="lang-bash"># Stop at first failure
|
|
pytest tests/ --pdb
|
|
|
|
# Stop at all failures
|
|
pytest tests/ --pdb --maxfail=5
|
|
|
|
# Use ipdb instead of pdb
|
|
pytest tests/ --pdb --pdbcls=IPython.terminal.debugger:Pdb</code></pre>
|
|
<p><strong>Example</strong>:</p>
|
|
<pre><code class="lang-python">def test_calculation():
|
|
result = calculate(5, 0)
|
|
assert result == 5 # Fails, drops into pdb
|
|
|
|
# Terminal shows:
|
|
# >>>>>>>>>>>>>>>>>>>> PDB set_trace >>>>>>>>>>>>>>>>>>>
|
|
# (Pdb) p result
|
|
# (Pdb) l</code></pre>
|
|
<h3>pytest Fixtures in Debugger</h3>
|
|
<pre><code class="lang-python">import pytest
|
|
|
|
@pytest.fixture
|
|
def sample_data():
|
|
return [1, 2, 3, 4, 5]
|
|
|
|
def test_with_fixture(sample_data):
|
|
breakpoint() # Can inspect sample_data here
|
|
assert sum(sample_data) == 15</code></pre>
|
|
<h3>Debugging Test Setup/Teardown</h3>
|
|
<pre><code class="lang-bash"># Show setup/teardown output
|
|
pytest tests/ --pdb --capture=no
|
|
|
|
# Or -s shorthand
|
|
pytest tests/ --pdb -s</code></pre>
|
|
<hr>
|
|
<h2>Remote Debugging</h2>
|
|
<h3>debugpy (VSCode Remote Debugging)</h3>
|
|
<p><strong>Install debugpy</strong>:</p>
|
|
<pre><code class="lang-bash">uv add --dev debugpy</code></pre>
|
|
<p><strong>Remote script setup</strong>:</p>
|
|
<pre><code class="lang-python"># remote_app.py
|
|
import debugpy
|
|
|
|
# Wait for debugger to attach
|
|
debugpy.listen(("0.0.0.0", 5678))
|
|
print("Waiting for debugger attach...")
|
|
debugpy.wait_for_client()
|
|
print("Debugger attached!")
|
|
|
|
# Your code here
|
|
def main():
|
|
for i in range(10):
|
|
print(f"Iteration {i}")
|
|
|
|
if __name__ == "__main__":
|
|
main()</code></pre>
|
|
<p><strong>VSCode launch.json</strong>:</p>
|
|
<pre><code class="lang-json">{
|
|
"version": "0.2.0",
|
|
"configurations": [
|
|
{
|
|
"name": "Python: Attach",
|
|
"type": "python",
|
|
"request": "attach",
|
|
"connect": {
|
|
"host": "remote-server.com",
|
|
"port": 5678
|
|
},
|
|
"pathMappings": [
|
|
{
|
|
"localRoot": "${workspaceFolder}",
|
|
"remoteRoot": "/app"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
}</code></pre>
|
|
<p><strong>SSH tunnel</strong>:</p>
|
|
<pre><code class="lang-bash"># Forward remote port to local
|
|
ssh -L 5678:localhost:5678 [email protected]
|
|
|
|
# In another terminal:
|
|
# Start VSCode debug with "Python: Attach"</code></pre>
|
|
<h3>pdb Remote Debugging</h3>
|
|
<p><strong>Simple remote pdb</strong>:</p>
|
|
<pre><code class="lang-python"># On remote machine
|
|
import pdb
|
|
import sys
|
|
|
|
class RemotePdb(pdb.Pdb):
|
|
def __init__(self, port=4444):
|
|
import socket
|
|
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
self.sock.bind(('0.0.0.0', port))
|
|
self.sock.listen(1)
|
|
print(f"Waiting for connection on port {port}...")
|
|
(clientsocket, address) = self.sock.accept()
|
|
handle = clientsocket.makefile('rw')
|
|
pdb.Pdb.__init__(self, stdin=handle, stdout=handle)
|
|
|
|
# Use it
|
|
RemotePdb(port=4444).set_trace()
|
|
|
|
# Connect from local machine:
|
|
# telnet remote-server.com 4444</code></pre>
|
|
<hr>
|
|
<h2>Performance Profiling</h2>
|
|
<h3>cProfile</h3>
|
|
<p><strong>Profile script</strong>:</p>
|
|
<pre><code class="lang-bash"># Profile entire script
|
|
python -m cProfile -s cumulative script.py
|
|
|
|
# Save profile data
|
|
python -m cProfile -o output.prof script.py</code></pre>
|
|
<p><strong>Profile in code</strong>:</p>
|
|
<pre><code class="lang-python">import cProfile
|
|
import pstats
|
|
|
|
def profile_function():
|
|
profiler = cProfile.Profile()
|
|
profiler.enable()
|
|
|
|
# Code to profile
|
|
result = expensive_calculation()
|
|
|
|
profiler.disable()
|
|
stats = pstats.Stats(profiler)
|
|
stats.sort_stats('cumulative')
|
|
stats.print_stats(10) # Top 10 functions
|
|
|
|
return result</code></pre>
|
|
<p><strong>Analyze profile</strong>:</p>
|
|
<pre><code class="lang-python">import pstats
|
|
|
|
# Load profile
|
|
stats = pstats.Stats('output.prof')
|
|
|
|
# Sort and print
|
|
stats.sort_stats('cumulative').print_stats(20)
|
|
stats.sort_stats('time').print_stats(20)
|
|
|
|
# Filter by function name
|
|
stats.print_stats('my_function')</code></pre>
|
|
<h3>line_profiler</h3>
|
|
<p><strong>Install</strong>:</p>
|
|
<pre><code class="lang-bash">uv add --dev line-profiler</code></pre>
|
|
<p><strong>Usage</strong>:</p>
|
|
<pre><code class="lang-python"># Add @profile decorator
|
|
@profile
|
|
def slow_function():
|
|
total = 0
|
|
for i in range(1000000):
|
|
total += i
|
|
return total
|
|
|
|
# Run with kernprof
|
|
# kernprof -l -v script.py</code></pre>
|
|
<p><strong>Output shows line-by-line timing</strong>:</p>
|
|
<pre><code>Line # Hits Time Per Hit % Time Line Contents
|
|
==============================================================
|
|
3 @profile
|
|
4 def slow_function():
|
|
5 1 2.0 2.0 0.0 total = 0
|
|
6 1000001 300000.0 0.3 50.0 for i in range(1000000):
|
|
7 1000000 300000.0 0.3 50.0 total += i
|
|
8 1 0.0 0.0 0.0 return total</code></pre>
|
|
<h3>memory_profiler</h3>
|
|
<p><strong>Install</strong>:</p>
|
|
<pre><code class="lang-bash">uv add --dev memory-profiler</code></pre>
|
|
<p><strong>Usage</strong>:</p>
|
|
<pre><code class="lang-python">from memory_profiler import profile
|
|
|
|
@profile
|
|
def memory_intensive():
|
|
big_list = [0] * (10 ** 7)
|
|
return sum(big_list)
|
|
|
|
# Run: python -m memory_profiler script.py</code></pre>
|
|
<hr>
|
|
<h2>Debugging Best Practices</h2>
|
|
<h3>Strategic Breakpoint Placement</h3>
|
|
<pre><code class="lang-python"># ❌ Bad: Too many breakpoints
|
|
for i in range(1000000):
|
|
breakpoint() # Stops 1M times!
|
|
process(i)
|
|
|
|
# ✅ Good: Conditional breakpoint
|
|
for i in range(1000000):
|
|
if i == 999999: # Last iteration only
|
|
breakpoint()
|
|
process(i)
|
|
|
|
# ✅ Better: Use logging for hot paths
|
|
import logging
|
|
for i in range(1000000):
|
|
logging.debug(f"Processing {i}")
|
|
process(i)</code></pre>
|
|
<h3>Debugging Strategies</h3>
|
|
<p><strong>Binary search for bug</strong>:</p>
|
|
<pre><code class="lang-python"># Start with breakpoint in middle
|
|
def long_function():
|
|
step1()
|
|
step2()
|
|
step3()
|
|
breakpoint() # Middle
|
|
step4()
|
|
step5()
|
|
step6()
|
|
|
|
# If bug before breakpoint, move up
|
|
# If bug after breakpoint, move down</code></pre>
|
|
<p><strong>Rubber duck debugging</strong>:</p>
|
|
<pre><code class="lang-python"># Explain code to debugger
|
|
def calculate(a, b):
|
|
breakpoint()
|
|
# "So a is 5, b is 0, and I'm dividing..."
|
|
# "Oh! Division by zero!"
|
|
return a / b</code></pre>
|
|
<hr>
|
|
<h2>Common Debugging Workflows</h2>
|
|
<h3>Debugging Import Errors</h3>
|
|
<pre><code class="lang-python"># Check import paths
|
|
import sys
|
|
print(sys.path)
|
|
|
|
# Debug module import
|
|
import importlib
|
|
spec = importlib.util.find_spec('mymodule')
|
|
print(spec) # None = not found</code></pre>
|
|
<h3>Debugging Async Code</h3>
|
|
<pre><code class="lang-python">import asyncio
|
|
|
|
async def debug_async():
|
|
await asyncio.sleep(1)
|
|
breakpoint() # Works in async functions
|
|
result = await fetch_data()
|
|
return result
|
|
|
|
# VSCode/PyCharm handle async debugging automatically</code></pre>
|
|
<h3>Debugging Decorators</h3>
|
|
<pre><code class="lang-python">from functools import wraps
|
|
|
|
def my_decorator(func):
|
|
@wraps(func)
|
|
def wrapper(*args, **kwargs):
|
|
breakpoint() # Debug decorator logic
|
|
result = func(*args, **kwargs)
|
|
return result
|
|
return wrapper
|
|
|
|
@my_decorator
|
|
def my_function():
|
|
pass</code></pre>
|
|
<h3>Debugging Comprehensions</h3>
|
|
<pre><code class="lang-python"># ❌ Hard to debug
|
|
result = [process(x) for x in data if x > 10]
|
|
|
|
# ✅ Easier to debug
|
|
result = []
|
|
for x in data:
|
|
if x > 10:
|
|
breakpoint() # Can inspect x
|
|
processed = process(x)
|
|
result.append(processed)</code></pre>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code>❌ NEVER: Leave breakpoint() in production code
|
|
→ Pauses production app, user sees debugger
|
|
|
|
❌ NEVER: Use print() instead of logging
|
|
→ Can't disable, pollutes output
|
|
|
|
❌ NEVER: Debug without reproducing bug first
|
|
→ Wastes time on wrong code path
|
|
|
|
❌ NEVER: Modify code while debugging without restarting
|
|
→ Changes not reflected, confusing state
|
|
|
|
❌ NEVER: Use debugger for performance issues
|
|
→ Use profiler instead (cProfile, line_profiler)
|
|
|
|
❌ NEVER: Debug optimized bytecode (.pyc)
|
|
→ Use source code (.py) for accurate debugging</code></pre>
|
|
<h3>Best Practices</h3>
|
|
<pre><code>✅ ALWAYS: Use breakpoint() instead of pdb.set_trace() (Python 3.7+)
|
|
✅ ALWAYS: Set PYTHONBREAKPOINT=ipdb.set_trace for enhanced debugging
|
|
✅ ALWAYS: Use conditional breakpoints in hot paths
|
|
✅ ALWAYS: Profile before optimizing (measure, don't guess)
|
|
✅ ALWAYS: Use logging for production debugging
|
|
✅ ALWAYS: Clean up debug code before committing</code></pre>
|
|
<hr>
|
|
<h2>Environment Variables</h2>
|
|
<h3>Useful Python Debug Variables</h3>
|
|
<pre><code class="lang-bash"># Set default breakpoint implementation
|
|
export PYTHONBREAKPOINT=ipdb.set_trace
|
|
|
|
# Disable all breakpoint() calls
|
|
export PYTHONBREAKPOINT=0
|
|
|
|
# Enable asyncio debug mode
|
|
export PYTHONASYNCIODEBUG=1
|
|
|
|
# Show warnings
|
|
export PYTHONWARNINGS=default
|
|
|
|
# Enable development mode (extra checks)
|
|
export PYTHONDEVMODE=1
|
|
|
|
# Show full tracebacks
|
|
export PYTHONFAULTHANDLER=1</code></pre>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>gdb-fundamentals.md</strong>: GDB for C/C++/Rust debugging</li><li><strong>lldb-macos-debugging.md</strong>: LLDB for macOS/iOS</li><li><strong>browser-devtools.md</strong>: Browser debugging tools</li><li><strong>remote-debugging.md</strong>: Remote debugging techniques</li><li><strong>test-debugging-strategies.md</strong>: Debugging test failures</li></ul>
|
|
<hr>
|
|
<h2>Summary</h2>
|
|
<p>Python provides comprehensive debugging tools for all scenarios:</p>
|
|
<ol><li><strong>pdb/ipdb</strong>: Built-in CLI debugging with post-mortem support</li><li><strong>VSCode/PyCharm</strong>: GUI debugging with breakpoints, watches, call stack</li><li><strong>pytest --pdb</strong>: Drop into debugger on test failures</li><li><strong>debugpy</strong>: Remote debugging for distributed systems</li><li><strong>cProfile/line_profiler</strong>: Performance profiling and optimization</li><li><strong>Async debugging</strong>: Native support in modern debuggers</li></ol>
|
|
<p><strong>Quick start</strong>:</p>
|
|
<pre><code class="lang-python"># Simple debugging
|
|
def my_function(x):
|
|
breakpoint() # Pause here
|
|
return x * 2
|
|
|
|
# VSCode debugging
|
|
# 1. Set breakpoint (click gutter)
|
|
# 2. Press F5
|
|
# 3. Use F10 (step over), F11 (step into)
|
|
|
|
# Test debugging
|
|
pytest tests/ --pdb --pdbcls=IPython.terminal.debugger:Pdb</code></pre>
|
|
<p>Master Python debugging for efficient development and troubleshooting.</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/debugging-python-debugging.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |