From 1766e45134e833720798db550d7d4e6425d7a7b3 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 23 Mar 2026 21:27:10 -0500 Subject: [PATCH] Add Start The Debugger When A Test Errors as a Python TIL --- README.md | 3 ++- .../start-the-debugger-when-a-test-errors.md | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 python/start-the-debugger-when-a-test-errors.md diff --git a/README.md b/README.md index 1909562..456ce8e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1765 TILs and counting..._ +_1766 TILs and counting..._ See some of the other learning resources I work on: @@ -1060,6 +1060,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Look Inside Pytest tmp_path](python/look-inside-pytest-tmp-path.md) - [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md) - [Parse Relative Time To datetime Object](python/parse-relative-time-to-datetime-object.md) +- [Start The Debugger When A Test Errors](python/start-the-debugger-when-a-test-errors.md) - [Store And Access Immutable Data In A Tuple](python/store-and-access-immutable-data-in-a-tuple.md) - [Test A Function With Pytest](python/test-a-function-with-pytest.md) - [Use pipx To Install End User Apps](python/use-pipx-to-install-end-user-apps.md) diff --git a/python/start-the-debugger-when-a-test-errors.md b/python/start-the-debugger-when-a-test-errors.md new file mode 100644 index 0000000..35dfa4c --- /dev/null +++ b/python/start-the-debugger-when-a-test-errors.md @@ -0,0 +1,27 @@ +# Start The Debugger When A Test Errors + +While working on [some +tests](https://github.com/jbranchaud/build-an-llm-from-scratch/blob/main/tests/chapter_02/test_bpe_tokenizer.py) +for my Byte Pair Encoding tokenizer, I was running into an unexpected test +failure. To better understand what was going on, I needed to inspect the state +of the program around the time the code raised an exception. + +Instead of needing to manually set a breakpoint at the correct spot to begin +debugging, I can run the test with the Pytest-supported `--pdb` flag. That's +short for _python debugger_. + +> Start the interactive Python debugger on errors or KeyboardInterrupt + +What this does during a test run is opens you up to the interactive Python +debugger at the exact moment an exception is raised. This gives you the ability +to inspect values of the program state at that point in execution which could +help inform the needed fix. + +```bash +uv run pytest -vv --pdb -k "test_train_bpe" +``` + +There I am running a specific test that matches against `-k "test_train_bpe"` +and the python debugger will start up if there is an error. + +See `uv run pytest --help` for more details.