Reading an error

The program crashed. Where do you look first?

$ python3 orders.py order.jsonTraceback (most recent call last): File "/home/ana/shop/orders.py", line 12, in <module>3 print(total(json.load(open(sys.argv[1])))) File "/home/ana/shop/orders.py", line 7, in total t += price(item) File "/home/ana/shop/orders.py", line 2, in price2 return item["price"] * item["qty"]TypeError: can't multiply sequence by non-int of type 'float'11Start at the last linethe kind of error, and what Python says2Then the frame above itthe file and line where it happened3Read upwards only if neededwho called that line, back to the startA traceback is read from the bottom: the last line is the error, the frame above it is where.The list is the chain of calls, oldest first, so the newest and most useful part is at the end. Here: a TypeError in price,on line 2. "Sequence" is Python’s word for text and lists: one of the two values on that line is text where a numberwas expected. Half of debugging is reading the message slowly, before changing anything.

A traceback lists the calls that led to an error, oldest first. Read the last line for what went wrong and the frame above it for where.

Common exceptions · Going deeper · 1 of 2

Eight exceptions cover most crashes, and each names a kind of mistake

ExceptionA line that raises itPython's messageUsually meansNameErrorprnt('hi')name 'prnt' is not defineda typo, or used before it was assignedTypeError'8080' + 1can only concatenate str (not "int") to strthe right operation on the wrong typeValueErrorint('eighty')invalid literal for int() with base 10: 'eighty'the right type, an impossible valueKeyErrorserver['port']'port'no such key: use .get(), or check firstIndexError[1, 2, 3][3]list index out of rangeoff by one, or the list is emptyAttributeErrorNone.strip()'NoneType' object has no attribute 'strip'something earlier returned NoneModuleNotFoundErrorimport yamllNo module named 'yamll'not installed, or the wrong venvFileNotFoundErroropen('missing.txt')[Errno 2] No such file or directory: 'missing.txt'a relative path, run from elsewhereThe class of the exception names the kind of mistake. Read it before the message.AttributeError on NoneType is rarely a fault on that line: a function further back returned None. Trace the value,not the line. SyntaxError and IndentationError differ in kind: Python finds them before it runs anything, so not oneline of the file executes. Messages are from Python 3.13; KeyError prints only the missing key.

Read the exception class first: it says what kind of mistake to look for.

The debugger · Going deeper · 2 of 2

breakpoint() stops the program so you can look at the values

orders.py, with one line addeddef total(order): t = 0 for item in order["items"]: breakpoint() t += price(item) return tAt the (Pdb) promptp exprprint a valuenrun the next linesstep into the call on this lineccontinue to the next breakpointqquitPython 3.13; the fault from the main page, cut down$ python3 orders.py> /home/ana/shop/orders.py(7)total()-> breakpoint()(Pdb) p item{'price': 4.5, 'qty': '2'}(Pdb) p type(item["qty"])<class 'str'>(Pdb) n> /home/ana/shop/orders.py(8)total()-> t += price(item)(Pdb) qbreakpoint() stops the program at that line and lets you question the live values.Here it shows at once that qty is the text '2', which the traceback could only hint at. To stop at a crash withoutediting anything, run python3 -m pdb -c continue orders.py; pytest --pdb does the same for a failing test.Remove breakpoint() before you commit. Setting PYTHONBREAKPOINT=0 switches every one of them off.

breakpoint() opens the debugger at that line: p prints, n steps, c continues.

Narrowing down

It worked last week. Which of 16 changes broke it?

1234567891011121314151617workedfailstest 1workstest 2failstest 3workstest 4failschange 12 broke it$ git bisect start HEAD 85eafc7Bisecting: 7 revisions left to test after this (roughly 3 steps)$ git bisect goodBisecting: 3 revisions left to test after this (roughly 2 steps)16 changes, found in 4 tests1,000 changes would take 10each test halves what is leftWhen it worked before and fails now, test the middle: each test removes half of the suspects.This needs one thing first: a way to make the fault appear on demand, one command that passes or fails. Then you neverread all sixteen changes; you test four. git bisect does the bookkeeping. The same halving works anywhere: half theinput file, half the configuration, half the steps of a pipeline.

With a known good state and a known bad one, test the middle and repeat: 16 suspects need 4 tests. git bisect automates it.

git bisect run · Going deeper

Give bisect a command and it finds the commit without you

git 2.43; pytest's own output left out$ git bisect start HEAD 560aea8Bisecting: 7 revisions left to test after this (roughly 3 steps)[a3390fa467ac6d05721f10307f20e139248ae279] change 9$ git bisect run python3 -m pytest -qrunning 'python3' '-m' 'pytest' '-q'Bisecting: 3 revisions left to test after this (roughly 2 steps)[f227778d7b2e19e59c88ddf5cff8e7c65c982fe0] change 13...56d1a97872715c3a1bf72be0db5cd641fe928816 is the first bad commitbisect found first bad commit$ git bisect resetSwitched to branch 'main'Exit codebisect marks the commit as0good: the fault is not here yet1 to 127bad: the fault is present125skip: this commit cannot be testedanything elsestop the whole bisect17 commits, 16 changes, one of them faulty.Tested: changes 9, 13, 11 and 12.git bisect run repeats your test at each step: exit code 0 means good, non-zero means bad.It tested four commits and named change 12, in seconds and with nobody watching. Any command will do: a test, a build,a script that searches a log. Have a script return 125 when a commit cannot be judged, for example when it does notbuild. Finish with git bisect reset: until then HEAD sits detached on a commit in the middle of history.

git bisect run uses the exit code of your test: 0 is good, non-zero is bad.

Fixing

How do you know the fix fixed it?

The test: the failing input, written downdef test_quantity_given_as_text(): order = {"items": [{"price": 4.5, "qty": "2"}]} assert total(order) == 9.0$ python3 -m pytest -qFAILED test_orders.py::test_quantity_given_as_text1 failed in 0.02sOne change- return item["price"] * item["qty"]+ return item["price"] * int(item["qty"])$ python3 -m pytest -q. [100%]1 passed in 0.01sChange one thing, run the same check, and keep that check as a test.The quantity arrived from a JSON file as the text "2". Write the smallest input that fails as a test and watch it fail:now you know the test sees the fault. Make one change. If the test passes, that change was the cause; change threethings at once and you cannot tell which. The test stays in the project, so this fault cannot come back unnoticed.

Reproduce the fault as a failing test, change one thing, and see the test pass. The test then guards against the fault returning.

AI assistants

An AI assistant drafts; you remain the author

Yousay what you want,and whyAssistantdrafts the codeand its testsCheckstests, linter,scansred: give it the errorYouread every lineof the diffwrong or unclear: explain, and try againA colleaguereviews thepull requestAn AI assistant drafts. You remain the author.It is quick at boilerplate, tests, first drafts and explaining unfamiliar code. It knows your systemonly as far as it is shown, and it carries no responsibility. Whoever opens the pull request answersfor every line in it, however the line was written. Generated code passes the same gates as any other.

It drafts. The checks run. You read every line.

Using AI safely

Treat generated code like a stranger's pull request

The riskHow it showsThe guardIt can be confidently wronga function or a package that does not exist✓run it, test it, check the documentationIt knows only what it is showncode that ignores your conventions✓give it the files, the error, the constraintsWhat you paste leaves your machinea secret or customer data in a prompt✓redact first; use the approved toolAn agent can run commandsa wrong delete, a push to main✓a branch, least privilege, no production keysTreat generated code as you would a pull request from a stranger.Read it, run it and question it before it becomes yours. Be most careful where mistakes cost most:security, money, deleting data, infrastructure. An unknown package in a suggestion may be an inventedname, and attackers register such names, so check that a dependency is real before installing it.

Verify what it writes. Protect what you paste. Limit what it can do.

Using AI safely · Going deeper

Asking well

A weak requestfix the login bugThe assistant must guess everything.A strong requestGoalSafari users get a 401 straight after logging in.Contextauth.py, and the failing test, are attached.ConstraintsDo not change the token format.Done whentest_login_safari passes, and nothing else fails.The quality of the answer follows the quality of the request.Say what you want and why, show the relevant code and the exact error, state what must not change,and say how you will know it is done. Ask for small steps and a test with each. When an answer iswrong, say what is wrong with it: a correction teaches more than a repeated request.

Goal, context, constraints, and what done means.

Lesson complete

You finished “Debugging and working with AI tools”

Nicely done.

Open in a new tab