A practical guide to debugging Python with pdb
Python tracebacks show where an exception surfaced, but they rarely explain why the data became invalid on the way there. The debugger built into Python lets you pause a running program, inspect variables and move through statements one at a time. That turns a vague stack trace into a controlled investigation, without scattering temporary print statements through otherwise sound business logic.
Python’s standard debugger, commonly called pdb, is available without installing anything. Put breakpoint() beside the suspicious statement, or launch a file with python -m pdb app.py. At the prompt, next runs the current line and moves down, step enters a call, and continue resumes the program. Variables are not merely visible; they can be evaluated and altered, so you can test a proposed correction before editing the source.
That makes pdb well suited to the working habits of Australian development teams. Python meetups in Sydney and Melbourne share debugging techniques, and many local businesses use the language for operational scripts, data processing and internal tools. It is especially useful when a failure depends on local conditions, including different daylight-saving clocks across Australian states or a scheduled reconciliation job overlapping the familiar arvo coffee break.
Effective debugging is a controlled dialogue with the program. You need a trigger, a place to pause and enough context to compare expectations with reality. The most productive sessions ask one narrow question at a time: which value first became wrong, which branch should have been taken, or which state changed unexpectedly? That framing prevents an interactive prompt from becoming an unstructured tour of the codebase.
Establish a reproducible failure
Begin by reproducing the failure with the smallest dependable command. Record the Python version, operating system, dependency versions, input data and environment variables involved. A command that worked on one workstation can fail on another because an API endpoint, locale or time zone differs. python -VV, platform.platform() and a careful look at the active virtual environment often expose those differences before they become false clues.
Next, separate what is known from what is assumed. Turn the report into “the total is wrong for this order”, then find where the expected and actual totals diverge. Add a temporary log only for a timestamp or correlation identifier, and remove it afterward. For organisations covered by Australia’s Privacy Act 1988, keep customer names, addresses and payment identifiers out of casual logs; the OAIC’s Notifiable Data Breaches scheme makes careful handling of compromised personal information a legal concern, not merely good hygiene.
Reduce the input while retaining the fault. A dozen records may become three, but the reduced case must still take the same bad branch. If the bug appears only in a test suite, run that test alone before altering fixtures. If it appears after a deployment, compare configuration and data shape rather than assuming the newest commit is responsible. This discipline prevents the debugger from becoming a place where random edits merely hide the original problem.
A debugging notebook benefits from the same visual restraint as a clear website. The simple landing design offers an analogy: generous whitespace, legible typography, restrained photography and a nature-inspired palette keep attention on one element at a time, just as a clear command and one hypothesis make the next action obvious.
Place breakpoints where meaning changes
There are two common ways to enter pdb. breakpoint() is concise and works in Python 3.7 and later; it calls the configurable sys.breakpointhook, so a team can standardise behaviour through PYTHONBREAKPOINT. Starting with python -m pdb app.py is useful when you cannot edit the source immediately or want the interpreter to stop after an uncaught exception. Older code may use the explicit pdb.set_trace() call.
Choose a breakpoint where meaning changes: after parsing but before calculation, when a response crosses into a domain object, or immediately before a value is returned. A tbreak at the next line is often enough. For a selective stop, use a condition such as break totals.py:42, order["status"] == "failed". Conditional stops keep noisy loops manageable and preserve the context that made one record exceptional.
Inspect the source around the stop before pressing a motion command. where identifies the current frame, while display can show expressions automatically whenever execution pauses. A breakpoint inside a library may be reached through several wrappers, so note the application frame you care about rather than tracing blindly into every imported function. If source and .pyc files are out of sync, confirm that Python is loading the checkout you think it is.
Move through execution with intent
Moving through code should answer a specific question. Use next when the current function is probably correct and you want to follow its statements; use step when the caller may have passed bad data into it. return leaves the current function, while continue resumes until the next breakpoint. These distinctions keep the session focused: repeatedly stepping into json.loads or a framework helper rarely helps when the defect sits in the value constructed before the call.
When the interesting state is already visible, interrogate it directly. p expression prints a value, pp expression offers expanded formatting, and args lists a function’s arguments. In a frame, p locals() and p globals() show the names available to that scope. up and down move through the call stack, which is valuable when a helper receives valid-looking data but its caller supplied the wrong customer, account or currency amount.
Treat every mutation as an experiment. Changing a local variable can prove a hypothesis, but it does not correct the original input, and changing a dictionary can affect objects elsewhere in the program. Prefer understanding the transition before editing anything. Async code needs extra care: stop around await boundaries, inspect the coroutine’s inputs and outputs, and resume in small increments. For generators, observe each yielded value instead of assuming the consumer will transform it as intended.
Inspect tests and post-mortem failures
Tests provide an excellent controlled failure. Run pytest --pdb to enter the debugger automatically when a test fails, or use pytest --trace when the problem must be observed from the test’s first line. For an uncaught exception outside pytest, python -m pdb app.py opens a post-mortem session with the traceback available. Inside an exception handler, pdb.post_mortem() can expose the active exception; p sys.exc_info()[1] shows its value and p sys.exc_info()[1].args shows its arguments.
Work from the innermost useful frame, not necessarily the final traceback line. A KeyError may be more informative than the generic KeyError text when the missing key came from a renamed field three layers earlier. Inspect local inputs, the expected schema and the transformation that connected them. Then rerun the same test after a fix; a debugger session is evidence-gathering, while an automated regression test is the durable proof that the defect has gone.
If your Python code parses HTML, save a copy of a page with structured headings, such as programme tier details, and inspect that local copy instead of repeatedly hitting the live server. Treat the file as inert test data, remove unnecessary content and obtain permission before collecting from any real service. Stable fixtures make parser failures reproducible without turning debugging into uncontrolled network traffic.
Make debugging repeatable and safe
A reliable debugging routine has a simple rhythm: reproduce, narrow, inspect, change one thing, rerun and preserve the result as a test. Keep notes about the command, input and what you learned so the next engineer does not repeat the search. Use the debugger to learn which invariant broke, then make the smallest source change that restores it and add a focused regression test. The strongest outcome is not an interactive session that happened to work once; it is a short, repeatable check that fails before the correction and passes afterwards.
Commercial tooling deserves the same scrutiny. A debugging product or consumer support service sold in Australia is covered by the Australian Consumer Law, including guarantees on acceptable quality and fitness where a disclosed purpose was relied upon, as well as claims made in advertising. Local vendors should state supported Python versions, where uploaded code and logs are stored, and what happens to them. Transparent data handling is part of the product, not an afterthought.
Never leave breakpoint() in a production path, and do not expose an interactive debugger to a network or public container. A debugger permits arbitrary code execution, so production diagnosis should rely on structured logs, metrics, tracing and protected diagnostic access. If a log contains personal information, apply the Privacy Act’s collection, use, disclosure and security requirements, limit access and define a deletion period. Redact at the logging boundary rather than after a log has shipped. The safest debugger is the one that never reaches a live production path.