Product case study · November 25, 2026

Ask Claude Code to put frame 2 before frame 10

Repair a Python file sorter with Claude Code. Specify numeric order, leading-zero ties and invalid names, then verify the change with fixed regression tests.

Reading time
6 min
Checked
Nov 25, 2026
Superbash default editorial graphic used for this numbered-file sorting tutorial.
Make the sequence explicit before an agent changes the sort.
Bottom line

Define the filename grammar and tie rule before asking an agent for natural sorting. A short numeric key can solve a narrow, well-specified job.

Your exported frames are all present, but the preview jumps from frame 1 to frame 10 and then back to frame 2. Sorting the filenames did exactly what you asked. It compared text where your workflow needed a number.

Give Claude Code a small, explicit repair: order one known filename format without renaming files or changing the caller’s list. The interesting decision is what to do with frame-02.png and frame-2.png, which carry the same numeric value.

You need Bash, Python 3, and an installed, signed-in Claude Code. The Python baseline and reference repair below were tested locally. The agent prompt is an authored exercise, not a recorded Claude run. Official documentation was checked November 25, 2026.

Reproduce the wrong sequence

Create a disposable practice folder. This exercise sorts strings; it does not open, rename or render any image files.

frame_lab=$(mktemp -d /tmp/claude-frame-order.XXXXXX)
cd "$frame_lab"
cat > frames.py <<'PY'
def ordered_frames(names):
    return sorted(names)
PY
python3 - <<'PY'
from frames import ordered_frames
print(ordered_frames(["frame-2.png", "frame-10.png", "frame-1.png"]))
PY

The result is ['frame-1.png', 'frame-10.png', 'frame-2.png']. The shared prefix cannot distinguish these names; the first differing digit puts 1 before 2 even when it starts the number ten.

Python’s sorting guide documents a key argument for selecting what gets compared. We will compare the embedded integer while returning the original filename strings.

Decide what a frame name means

Save this contract as SPEC.md:

ordered_frames(names) receives a list of filename strings.
Accept only frame- followed by 1 to 9 ASCII digits, then .png.
Names are case-sensitive. Zero and leading zeros are allowed.
Return a new list ordered by the embedded integer, ascending.
For equal integers, preserve input order, including duplicates.
Keep the original filename spelling; do not rename or deduplicate.
Raise ValueError if any name is invalid; do not silently filter it out.
An empty input returns an empty list. Do not mutate the input list.
Change only frames.py. Keep this specification and tests unchanged.
Use the standard library; no filesystem access or package installation.

The nine-digit limit is a choice for this fictional exporter, not a Python requirement. Paths, uppercase extensions and arbitrary mixed filenames are outside its contract. If you need a general file-browser sort, define that wider behavior separately.

Preserving ties also has a consequence: equal-number files follow the order you supplied. This helper does not make an unordered directory listing deterministic. If your pipeline needs one fixed tie order across machines, specify and test a secondary key instead.

Save the following as test_frames.py:

import unittest
from frames import ordered_frames


class FrameOrderTests(unittest.TestCase):
    def test_numeric_order(self):
        self.assertEqual(
            ordered_frames(["frame-2.png", "frame-10.png", "frame-1.png"]),
            ["frame-1.png", "frame-2.png", "frame-10.png"],
        )

    def test_equal_numbers_keep_input_order(self):
        names = ["frame-2.png", "frame-002.png", "frame-02.png"]
        self.assertEqual(ordered_frames(names), names)

    def test_zero_and_largest_allowed_number(self):
        self.assertEqual(
            ordered_frames(["frame-999999999.png", "frame-0.png"]),
            ["frame-0.png", "frame-999999999.png"],
        )

    def test_invalid_names_are_rejected(self):
        invalid = [
            "frame-.png", "frame--1.png", "frame-1.PNG",
            "frame-1xpng", "folder/frame-1.png", "frame-1.png\n",
            "frame-١.png", "frame-1234567890.png",
        ]
        for name in invalid:
            with self.subTest(name=name):
                with self.assertRaises(ValueError):
                    ordered_frames(["frame-1.png", name])

    def test_input_and_duplicates_are_preserved(self):
        names = ["frame-2.png", "frame-1.png", "frame-1.png"]
        before = names.copy()
        result = ordered_frames(names)
        self.assertEqual(names, before)
        self.assertIsNot(result, names)
        self.assertEqual(result, ["frame-1.png", "frame-1.png", "frame-2.png"])

    def test_empty_input_returns_new_list(self):
        names = []
        result = ordered_frames(names)
        self.assertEqual(result, [])
        self.assertIsNot(result, names)

Run python3 -m unittest -v test_frames. Locally, the numeric-order and equal-number tests failed, along with all eight invalid-name subtests. The other three methods passed. Keep that failing baseline: it shows which requirements the plain text sort misses.

Give Claude Code the bounded task

Start claude in the practice folder and paste:

Read SPEC.md, frames.py and test_frames.py.
Run python3 -m unittest -v test_frames and report the baseline.
Explain why text sorting misorders the frames and how ties must behave.
Change only frames.py to satisfy the specification and unchanged tests.
Do not rename files, access other folders, install packages, delegate,
commit, or change the tests. Do not silently discard invalid names.
Run the same tests afterward and report the actual result.
Explain how the repair preserves leading zeros and duplicate entries.

Anthropic’s debugging workflow recommends supplying reproduction steps and checking the fix. Here the tests also prevent an agent from solving a different problem, such as normalizing all filenames to a padded format.

If Claude adds a third-party natural-sort package, point it back to the one-format contract. If it edits the expected order, restore the tests before reviewing the implementation. A claim that the function “handles filenames” is too broad; ask which exact names it accepts.

Compare with a reference repair

This implementation passes all six test methods:

import re


def ordered_frames(names):
    def frame_number(name):
        match = re.fullmatch(r"frame-([0-9]{1,9})\.png", name)
        if match is None:
            raise ValueError(f"invalid frame name: {name!r}")
        return int(match.group(1))

    return sorted(names, key=frame_number)

The regular-expression reference documents whole-string matching. [0-9] expresses our ASCII-only policy; the escaped dot requires a literal period. Extracting a number is not enough if the rest of the name is malformed.

The integer is only a comparison key. The returned values retain their original spelling. Python’s stable sort preserves input order for equal keys, which is why we do not add the filename as a second key. sorted() also produces a new list instead of sorting the caller’s list in place.

Run the unchanged test command yourself after the agent finishes. Python’s unittest documentation explains the command-line runner and assertions used here. Check both the passing output and the diff: the only implementation file should be frames.py.

This repair proves the ordering contract for the supplied cases. It does not prove files exist, that frame numbers are contiguous, or that an encoder will consume them in this order. Before connecting it to an export pipeline, inspect the ordered manifest and test that next boundary separately.

Sources

Checked November 25, 2026:

Put this to work

How a numeric sort key differs from sorting filename text.

Try

Give Claude Code a broken sorter, a filename contract and fixed tests.

Prove it worked

Compare the same six test methods before and after the repair.

Keep in view

  • Reproduce frame-10.png appearing before frame-2.png.
  • Define numeric order and preserve input order for equal frame numbers.
  • Reject malformed names instead of silently dropping files.
Learn the workflow: Start a scoped Claude Code project session