Start learning free

LESSON 99 OF 129 · AI ENGINEERING: BUILD YOUR OWN CODING AGENT

Show the Diff in Python

Practice

When your agent rewrites a file, the program prints Wrote: cart.py. That names the file and says nothing about what changed in it. A diff answers that: it lists the lines that went away, each marked with -, and the lines that came in, each marked with +.

Here is the diff of a shopping list where milk became oat milk. The two top lines name the file, the @@ line says where the change is, and a line with no mark did not change:

--- list.txt
+++ list.txt
@@ -1,2 +1,2 @@
-milk
+oat milk
 bread

Python's difflib module makes such a diff from two texts. A diff needs the text the file had before the change, so the old text is read before the file is written. Kept in a log, the same old text lets you undo a change: write it back, and the file is as it was.

In this lesson the course model makes a bad change first, and two more tests fail. With your code it takes the change back, then makes the real fix. Your program must print:

Step 3: write_file {'path': 'cart.py', 'text': 'FREE_SHIPPING_FROM = 0\nSHIPPIN...
--- cart.py
+++ cart.py
@@ -1,2 +1,2 @@
-FREE_SHIPPING_FROM = 5000
+FREE_SHIPPING_FROM = 0
 SHIPPING = 500
Wrote: cart.py
...
Step 5: undo_change {}
Undid: cart.py
...
Tests pass after the run: True
Changes in the log: 1

Your task: write make_diff(path, old, new) with difflib. In write_file, read the old text, print the diff and keep the change in the list changes, all before the file is written. Then finish undo_change, which writes the old text of the last change back, and give it to the model as a tool.


Assignment
Follow the Coding Tutorial to show a diff for every write, keep a log of the changes and undo the last one.


Hint
Order matters in write_file: read the old text, make the diff and add to the log first, and write the file last. A file that doesn't exist yet has the old text "".


STEP 1 OF 12
    Ctrl + Enter to check

    Ai Agent Show Diff in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free