Yeda AI Tips · #084

Español

pytest --lf: Re-run Only What Broke

Stop re-running your whole test suite after every fix. When you (or your AI coding agent) are mid-debug, a suite of 2,000 tests where 3 fail means every iteration wastes 99.85% of its runtime confirming things you already know. pytest ships a fix in two characters: --lf.

The mechanism: pytest's cross-run cache

Every pytest run writes which tests failed into a .pytest_cache directory in your project root. The rerun flags read that cache on the next invocation:

FlagLong formWhat it does
--lf--last-failedRe-run only the tests that failed last time
--ff--failed-firstRun last failures first, then the rest of the suite
--nf--new-firstRun newly added tests first (sorted by file mtime), then the rest
-xStop after the first failure
--maxfail=NStop after N failures
--sw--stepwiseStop at the first failure, resume from that test next run

The workhorse combo for a tight debug loop:

pytest --lf -x

Re-run only what broke, and bail the moment something is still broken. A red-to-green cycle on a 4-minute suite drops to seconds.

Why this matters more with AI agents

An AI coding agent debugging your code runs tests between every attempt — often 5–15 iterations for one bug. If each iteration runs the full suite, the agent spends most of its wall-clock time (and your patience) on tests that already pass. Worse, long feedback loops push agents toward guessing instead of verifying.

Put the fast loop in the agent's instructions (CLAUDE.md, AGENTS.md, system prompt — whatever your tool reads):

While fixing failing tests, iterate with pytest --lf -x. Run the full suite once at the end to confirm nothing else regressed.

That last sentence matters: --lf only re-runs known failures. A fix can break a test that passed last run, and --lf will never see it. Always finish with one full run.

Power-user moves

Rules of thumb

Resources

Building an AI feature? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog