▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
AI angle: refactor code with AI
Make old code idiomatic with AI, and verify nothing broke.
🎬 Video version coming soon — read it now
Refactoring means improving code's structure without changing what it does. AI is good at suggesting idiomatic rewrites using comprehensions, generators and the standard library. The danger is that a rewrite subtly changes behaviour. The professional method: lock in behaviour with checks first, then refactor.
Step 1: capture current behaviour
Before touching anything, record what the code produces for some inputs:
Step 2: ask for a refactor, with constraints
Step 3: verify
assert stops with an error if a result differs. This is a tiny test suite; the Production Python course turns it into proper pytest tests.
Watch for subtle changes
AI refactors commonly change:
- Return types: a
defaultdictinstead of adict, or a generator instead of a list - Ordering: using a set loses order
- Edge cases: empty input, None values, duplicate keys
- Exceptions: code that used to raise an error now silently skips the row, or the reverse
Notice dict(totals) in the example: without it, the return type would quietly change.
Judge readability yourself
"Idiomatic" isn't always "better". If the AI's version is shorter but you need a minute to understand it, keep the clearer one. The person maintaining the code at 11 pm before a release matters more than line count.
git diff shows exactly what changed and git restore takes you back.In one line
Record current outputs first, ask AI for a constrained refactor, assert the results still match, and keep the clearer version.
Share with a friend