Skip to content
IT Vizag
← Advanced Python Features

▶ 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

Lesson 9 of 10 · 2 min read

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:

🔒 Code example: sign up free (above) to unlock it.

Step 2: ask for a refactor, with constraints

🔒 Ready-to-copy prompt: sign up free (above) to unlock it.

Step 3: verify

🔒 Code example: sign up free (above) to unlock it.

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 defaultdict instead of a dict, 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.

Tip: Commit your code to git before an AI refactor. If anything goes wrong, 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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend