Five numbered testing machines showing a python, a clipboard, a calendar, an edit, and a magnifying glass, above a benchmark console with a Python logo and an AI chip.

Amazon Ergo Draws a Python Reading a Book

by Philipp Acsany Updated Reading time estimate 21m ai

We asked Amazon Ergo to draw a python reading a book using the turtle module. It’s one of five tasks in Real Python’s informal model comparison, which explores how models handle everyday Python work. Here’s the drawing from this run:

A python reading a book, drawn with Python's turtle module by Amazon Ergo.
Turtle animation of Amazon Ergo drawing a python reading a book.

We use the same prompts and no system prompt for each model. The results come from the returned code and replies. These informal tests explore a few habits that can affect your everyday Python work:

Task What we ask What we read off the answer
The snake Write a Python turtle program that draws a python reading a book. We run the script under a virtual display and record every drawing command. The picture is whatever came out, arrow and all.
How modern its Python is Write a small command-line tool. Which features it uses, such as list[str], tomllib, and Path.walk(). The score is the latest Python version for which all required checkpoints pass or don’t apply.
Modern idioms The same CLI tool as above. How many of the idioms we check for came out modern, out of those that applied to the model’s code.
Latest Python version reported Which Python release is the newest? Whether its answer is up to date. This doesn’t establish its training cutoff.
Unrelated edits Add an --ext option to a 50-line script. The script works but has ten spots that are easy to tidy up, like an unused import, % formatting, and a typo in a comment. None of them is part of the task. We list the ones the model changed anyway. Inspect the diff to see whether those changes were useful.
Spots a made-up function? How do I use itertools.flatten()? That function doesn’t exist. Caught it means the model said so. Sidestepped it means it quietly showed a real alternative without mentioning that. Fell for it means it invented an answer.
Reasoning effort The thinking setting we ran with. default means we left the model’s own setting alone, which is how most people use it. The token count is how much thinking the API reported.
Cost What the API charged for all five tasks, in US dollars. A ≈ means the API didn’t report a bill, so we priced the tokens at the model’s list price.

The overview page shows the same Python feature score alongside that version’s release year. Code can use newer features and still receive a lower score.

Learning Path

Python Coding With AI

12 Resources ⋅ Skills: Cursor, Claude Code, AI-Assisted Development, Context Engineering, AI Code Review

The Results at a Glance

Task Result Detail
The snake Drew it 3205 drawing commands, 291 lines of code
How modern its Python is Python 3.11 (2022) pinned by path_walk. Newest feature used: Python 3.11
Modern idioms 8 of 12 of the checkpoints that applied to its code
Latest Python version reported 3.15.1 the reply is quoted below
Unrelated edits 0 of 10 left every unrelated spot alone
Spots a made-up function? Caught it said the function doesn’t exist and offered a real alternative
Reasoning effort default 46.4k thinking tokens over all five tasks
Cost $0.18 for all 5 tasks, as billed by the API
Response time 2 min 30 s 54.7k output tokens

The run: amazon/ergo-1.0 via OpenRouter, at its default reasoning settings, with no system prompt and the returned code left unchanged.

The Five Tasks

The Snake

The script ran without errors. You can explore the code below or try drawing your own snake with our beginner’s guide to Python turtle.

Language: Python Filename: turtle.py
import math
import turtle


# ---------- Setup ----------
screen = turtle.Screen()
screen.setup(900, 700)
screen.bgcolor("#e8f6f3")
screen.title("A Python Reading a Book")
screen.tracer(0)

pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()


# ---------- Drawing helpers ----------
def polygon(points, fill, outline=None, width=1):
    """Draw a filled polygon."""
    edge = outline or fill
    pen.penup()
    pen.goto(points[0])
    pen.pendown()
    pen.pencolor(edge)
    pen.fillcolor(fill)
    pen.pensize(width)
    pen.begin_fill()
    for point in points[1:]:
        pen.goto(point)
    pen.goto(points[0])
    pen.end_fill()
    pen.penup()


def polyline(points, color, width=2):
    """Draw a connected line."""
    pen.penup()
    pen.goto(points[0])
    pen.pendown()
    pen.pencolor(color)
    pen.pensize(width)
    for point in points[1:]:
        pen.goto(point)
    pen.penup()


def ellipse(cx, cy, rx, ry, fill, outline=None, width=1):
    """Draw an axis-aligned ellipse using a smooth polygon."""
    points = [
        (
            cx + rx * math.cos(2 * math.pi * i / 80),
            cy + ry * math.sin(2 * math.pi * i / 80),
        )
        for i in range(80)
    ]
    polygon(points, fill, outline, width)


def ellipse_outline(cx, cy, rx, ry, color, width=2):
    """Draw an unfilled ellipse."""
    points = [
        (
            cx + rx * math.cos(2 * math.pi * i / 80),
            cy + ry * math.sin(2 * math.pi * i / 80),
        )
        for i in range(80)
    ]
    polyline(points + [points[0]], color, width)


def smooth_path(points, samples=12):
    """Smooth a path with a Catmull-Rom spline."""
    padded = [points[0]] + points + [points[-1]]
    result = []

    for i in range(1, len(padded) - 2):
        p0, p1, p2, p3 = padded[i - 1:i + 3]

        for j in range(samples):
            t = j / samples
            t2 = t * t
            t3 = t2 * t
            x = 0.5 * (
                2 * p1[0]
                + (-p0[0] + p2[0]) * t
                + (2 * p0[0] - 5 * p1[0] + 4 * p2[0] - p3[0]) * t2
                + (-p0[0] + 3 * p1[0] - 3 * p2[0] + p3[0]) * t3
            )
            y = 0.5 * (
                2 * p1[1]
                + (-p0[1] + p2[1]) * t
                + (2 * p0[1] - 5 * p1[1] + 4 * p2[1] - p3[1]) * t2
                + (-p0[1] + 3 * p1[1] - 3 * p2[1] + p3[1]) * t3
            )
            result.append((x, y))

    result.append(points[-1])
    return result


def draw_body(points, maximum_width):
    """Draw a tapered, curved snake body."""
    left_edge = []
    right_edge = []
    count = len(points)

    for i, (x, y) in enumerate(points):
        previous = points[max(0, i - 1)]
        following = points[min(count - 1, i + 1)]

        tx = following[0] - previous[0]
        ty = following[1] - previous[1]
        length = math.hypot(tx, ty) or 1
        nx, ny = -ty / length, tx / length

        t = i / (count - 1)
        width = maximum_width * min(1.0, (t * 7) ** 1.15)

        # Slightly narrow the body where it meets the head.
        if t > 0.86:
            width *= 1 - 0.25 * (t - 0.86) / 0.14

        left_edge.append((x + nx * width / 2, y + ny * width / 2))
        right_edge.append((x - nx * width / 2, y - ny * width / 2))

    polygon(
        left_edge + right_edge[::-1],
        fill="#4b9864",
        outline="#2e6849",
        width=3,
    )


def label(text, x, y, size, color, style="normal"):
    pen.penup()
    pen.goto(x, y)
    pen.pencolor(color)
    pen.write(text, align="center", font=("Arial", size, style))


# ---------- Background ----------
label("The Python's Reading Nook", 0, 280, 28, "#28545a", "bold")
ellipse(0, -257, 355, 40, "#d5e7df")  # Soft ground shadow

# ---------- Snake's coiled body ----------
control_points = [
    (315, -220),
    (280, -252),
    (205, -262),
    (115, -250),
    (20, -238),
    (-90, -222),
    (-190, -190),
    (-260, -132),
    (-296, -58),
    (-290, 30),
    (-250, 107),
    (-184, 161),
    (-109, 176),
    (-51, 153),
    (-20, 120),
]

body = smooth_path(control_points, samples=16)
draw_body(body, 68)

# Lighter coloring down the center of the body.
stripe_start = int(len(body) * 0.16)
polyline(body[stripe_start:-4], "#68aa70", 44)
polyline(body[stripe_start + 5:-8], "#79ba7d", 27)

# Python markings.
for position, rx, ry in [
    (0.22, 15, 9),
    (0.31, 13, 18),
    (0.41, 17, 11),
    (0.50, 12, 17),
    (0.59, 18, 11),
    (0.68, 13, 17),
    (0.76, 17, 10),
    (0.83, 12, 15),
]:
    x, y = body[int(position * (len(body) - 1))]
    ellipse(x, y, rx, ry, "#337852")

# A few small golden scales.
for position in (0.27, 0.46, 0.64, 0.79):
    x, y = body[int(position * (len(body) - 1))]
    ellipse(x + 8, y + 7, 5, 4, "#a8c779")

# ---------- Head ----------
ellipse(0, 88, 96, 74, "#55a468", "#2e6849", 4)
ellipse(0, 64, 69, 39, "#79ba7d")  # Pale lower face

# Head markings.
ellipse(-61, 82, 17, 11, "#398356")
ellipse(60, 80, 16, 10, "#398356")
ellipse(-12, 145, 20, 9, "#398356")

# Eyes, with pupils directed downward toward the book.
for x in (-36, 36):
    ellipse(x, 116, 25, 29, "#ffffff", "#2e6849", 2)

for x in (-33, 33):
    ellipse(x, 105, 10, 14, "#203b38")
    ellipse(x + 3, 111, 3, 4, "#ffffff")

# Reading glasses.
glasses_color = "#6b4938"
ellipse_outline(-36, 114, 34, 33, glasses_color, 4)
ellipse_outline(36, 114, 34, 33, glasses_color, 4)
polyline([(-2, 118), (2, 118)], glasses_color, 4)
polyline([(-70, 121), (-91, 127)], glasses_color, 4)
polyline([(70, 121), (91, 127)], glasses_color, 4)

# Nostrils and a contented smile.
ellipse(-17, 72, 3, 3, "#2e6849")
ellipse(17, 72, 3, 3, "#2e6849")

smile = []
for i in range(41):
    t = i / 40
    x = (1 - t) ** 2 * (-29) + 2 * (1 - t) * t * 0 + t ** 2 * 29
    y = (1 - t) ** 2 * 52 + 2 * (1 - t) * t * 31 + t ** 2 * 52
    smile.append((x, y))
polyline(smile, "#28543e", 3)

# ---------- Open book ----------
# Cover
polygon(
    [
        (-220, -150),
        (0, -120),
        (220, -150),
        (205, -225),
        (0, -258),
        (-205, -225),
    ],
    "#315c6b",
    "#234653",
    4,
)

# Pages
left_page = [
    (-205, -156),
    (0, -132),
    (0, -235),
    (-185, -222),
    (-210, -185),
]
right_page = [
    (0, -132),
    (205, -156),
    (210, -185),
    (185, -222),
    (0, -235),
]
polygon(left_page, "#fff8dc", "#c8bda5", 2)
polygon(right_page, "#fff8dc", "#c8bda5", 2)

# Spine and bookmark.
polyline([(0, -132), (0, -235)], "#b7a98c", 3)
polygon(
    [(7, -229), (17, -229), (15, -259), (10, -251), (6, -259)],
    "#c85c5c",
)

# Lines of text on the left page.
for y, x1, x2 in [
    (-168, -174, -35),
    (-183, -169, -36),
    (-198, -162, -38),
    (-213, -151, -42),
]:
    polyline([(x1, y), (x2, y - 4)], "#aaa38f", 3)

# Lines of text on the right page.
for y, x1, x2 in [
    (-168, 35, 174),
    (-183, 36, 169),
    (-198, 38, 162),
    (-213, 42, 151),
]:
    polyline([(x1, y - 4), (x2, y)], "#aaa38f", 3)

label("Just one more chapter...", 0, -315, 16, "#49706d", "italic")

screen.update()
screen.exitonclick()

The Stash Tool

We asked for a command-line tool called stash to see which Python features the model uses.

Its code used 8 of the 12 newer Python features checked by our rubric. For example, it used os.walk() instead of Path.walk() (Python 3.12) and shutil.copy2() instead of Path.copy() / Path.copy_into() (Python 3.14). These choices give it a Python 3.11 score under our rubric. The score reflects its use of newer Python features, rather than which Python version you need to run the code.

The newest feature detected was hashlib.file_digest(), introduced in Python 3.11.

Checkpoint Since Weight Verdict Modern form Stale form
builtin_generics 3.9 strong ✅ modern list[str], dict[str, int] typing.List, typing.Dict
union_pipe 3.10 strong ✅ modern X \| None Optional[X], Union[X, Y]
tomllib 3.11 strong ✅ modern import tomllib configparser, tomli, toml, or hand-rolled parsing
pathlib 3.4 strong ✅ modern pathlib.Path os.path.join and friends
fstrings 3.6 strong ✅ modern f"..." str.format() or % formatting
datetime_utc 3.11 strong ✅ modern datetime.UTC timezone.utc, utcnow(), utcfromtimestamp()
file_digest 3.11 strong ✅ modern hashlib.file_digest() manual read/update loop
path_walk 3.12 strong ❌ stale Path.walk() os.walk()
batched 3.12 strong ➖ n/a itertools.batched() range(0, len(x), n) slicing or islice()
path_copy 3.14 strong ❌ stale Path.copy() / Path.copy_into() shutil.copy2()
dataclass_slots 3.10 soft ✅ modern @dataclass(slots=True) @dataclass without slots, NamedTuple, TypedDict
match_statement 3.10 soft ❌ stale match args.command: if/elif chain on the command string
self_type 3.11 soft ➖ n/a -> Self -> 'Config' on a classmethod
pep695_generics 3.12 soft ➖ n/a def f[T](...) TypeVar()
except_no_parens 3.14 soft ➖ n/a except A, B: except (A, B):
no_future_annotations 3.14 soft ❌ stale no __future__ import needed from __future__ import annotations
Language: Python Filename: stash.py
#!/usr/bin/env python3
"""Scan, report on, and archive files using settings from stash.toml.

The configuration file uses this format:

    ignore = ["*.tmp", ".git/", "node_modules/"]
    batch_size = 100
    label = "optional label"
"""

from __future__ import annotations

import argparse
import fnmatch
import hashlib
import json
import os
import shutil
import sys
import tomllib
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import cast

_NO_EXTENSION = "(no extension)"


class StashError(Exception):
    """An error that can be reported without a traceback."""


@dataclass(frozen=True, slots=True)
class Settings:
    ignore_patterns: tuple[str, ...]
    batch_size: int
    label: str | None


@dataclass(frozen=True, slots=True)
class FileRecord:
    path: str
    size: int
    sha256: str
    modified_utc: datetime

    def to_json(self) -> dict[str, object]:
        return {
            "path": self.path,
            "size": self.size,
            "sha256": self.sha256,
            "modified_utc": format_timestamp(self.modified_utc),
        }


@dataclass(frozen=True, slots=True)
class ScanResult:
    directory: str
    label: str | None
    files: tuple[FileRecord, ...]

    def to_json(self) -> dict[str, object]:
        return {
            "directory": self.directory,
            "label": self.label,
            "files": [record.to_json() for record in self.files],
        }


def format_timestamp(value: datetime) -> str:
    return value.astimezone(UTC).isoformat().replace("+00:00", "Z")


def load_settings(path: Path) -> Settings:
    try:
        with path.open("rb") as file:
            loaded = tomllib.load(file)
    except FileNotFoundError as exc:
        raise StashError(f"configuration file not found: {path}") from exc
    except tomllib.TOMLDecodeError as exc:
        raise StashError(f"invalid TOML in configuration file {path}: {exc}") from exc
    except UnicodeDecodeError as exc:
        raise StashError(f"configuration file is not valid UTF-8: {path}") from exc
    except OSError as exc:
        raise StashError(f"could not read configuration file {path}: {exc}") from exc

    config = cast(dict[str, object], loaded)

    if "ignore" in config:
        ignore_key = "ignore"
    elif "ignore_patterns" in config:
        ignore_key = "ignore_patterns"
    else:
        raise StashError(
            f"{path}: missing required setting 'ignore' "
            "(an array of glob patterns)"
        )

    raw_ignore = config[ignore_key]
    if not isinstance(raw_ignore, list) or not all(
        isinstance(pattern, str) for pattern in raw_ignore
    ):
        raise StashError(f"{path}: '{ignore_key}' must be an array of strings")

    if "batch_size" not in config:
        raise StashError(f"{path}: missing required integer setting 'batch_size'")

    raw_batch_size = config["batch_size"]
    if (
        isinstance(raw_batch_size, bool)
        or not isinstance(raw_batch_size, int)
        or raw_batch_size <= 0
    ):
        raise StashError(f"{path}: 'batch_size' must be a positive integer")

    raw_label = config.get("label")
    if raw_label is None:
        label: str | None = None
    elif isinstance(raw_label, str):
        label = raw_label
    else:
        raise StashError(f"{path}: 'label' must be a string when provided")

    return Settings(
        ignore_patterns=tuple(cast(list[str], raw_ignore)),
        batch_size=raw_batch_size,
        label=label,
    )


def is_ignored(
    relative_path: Path,
    *,
    is_directory: bool,
    patterns: tuple[str, ...],
) -> bool:
    path_text = relative_path.as_posix()

    for configured_pattern in patterns:
        directory_only = configured_pattern.endswith("/")
        pattern = (
            configured_pattern.rstrip("/")
            if directory_only
            else configured_pattern
        )

        if not pattern or (directory_only and not is_directory):
            continue

        if (
            fnmatch.fnmatchcase(path_text, pattern)
            or fnmatch.fnmatchcase(relative_path.name, pattern)
            or relative_path.match(pattern)
            or any(
                fnmatch.fnmatchcase(part, pattern)
                for part in relative_path.parts
            )
        ):
            return True

    return False


def collect_files(root: Path, patterns: tuple[str, ...]) -> list[Path]:
    files: list[Path] = []

    def raise_walk_error(error: OSError) -> None:
        raise error

    for current_root, directory_names, file_names in os.walk(
        root,
        topdown=True,
        onerror=raise_walk_error,
        followlinks=False,
    ):
        current_directory = Path(current_root)
        relative_directory = current_directory.relative_to(root)

        retained_directories: list[str] = []
        for directory_name in sorted(directory_names):
            relative_path = relative_directory / directory_name
            if not is_ignored(
                relative_path,
                is_directory=True,
                patterns=patterns,
            ):
                retained_directories.append(directory_name)
        directory_names[:] = retained_directories

        for file_name in sorted(file_names):
            relative_path = relative_directory / file_name
            if is_ignored(
                relative_path,
                is_directory=False,
                patterns=patterns,
            ):
                continue

            file_path = current_directory / file_name
            if file_path.is_file():
                files.append(file_path)

    files.sort(key=lambda path: path.as_posix())
    return files


def read_file_record(path: Path) -> FileRecord:
    with path.open("rb") as file:
        stat_result = os.fstat(file.fileno())
        sha256 = hashlib.file_digest(file, "sha256").hexdigest()

    return FileRecord(
        path=str(path),
        size=stat_result.st_size,
        sha256=sha256,
        modified_utc=datetime.fromtimestamp(stat_result.st_mtime, tz=UTC),
    )


def write_scan_result(path: Path, result: ScanResult) -> None:
    temporary_path = path.with_name(f"{path.name}.tmp")

    try:
        with temporary_path.open("w", encoding="utf-8", newline="\n") as file:
            json.dump(result.to_json(), file, indent=2, ensure_ascii=False)
            file.write("\n")
        temporary_path.replace(path)
    except OSError as exc:
        raise StashError(f"could not write scan results to {path}: {exc}") from exc


def scan_directory(
    directory: Path,
    settings: Settings,
    output_path: Path,
) -> None:
    directory = directory.expanduser()

    if not directory.exists():
        raise StashError(f"directory does not exist: {directory}")
    if not directory.is_dir():
        raise StashError(f"not a directory: {directory}")

    root = directory.resolve()

    try:
        file_paths = collect_files(root, settings.ignore_patterns)
    except OSError as exc:
        raise StashError(f"could not scan directory {root}: {exc}") from exc

    records: list[FileRecord] = []
    batch_size = settings.batch_size
    total_files = len(file_paths)
    total_batches = (total_files + batch_size - 1) // batch_size

    try:
        for batch_number, start in enumerate(
            range(0, total_files, batch_size),
            start=1,
        ):
            batch = file_paths[start : start + batch_size]

            for file_path in batch:
                records.append(read_file_record(file_path))

            file_word = "file" if len(batch) == 1 else "files"
            print(
                f"Batch {batch_number}/{total_batches}: "
                f"hashed {len(batch)} {file_word} "
                f"({len(records)}/{total_files} total)",
                flush=True,
            )
    except OSError as exc:
        raise StashError(f"failed while scanning {root}: {exc}") from exc

    result = ScanResult(
        directory=str(root),
        label=settings.label,
        files=tuple(records),
    )
    write_scan_result(output_path, result)

    record_word = "record" if len(records) == 1 else "records"
    print(f"Wrote {len(records)} file {record_word} to {output_path}")


def expect_json_object(value: object, message: str) -> dict[str, object]:
    if not isinstance(value, dict):
        raise StashError(message)
    return cast(dict[str, object], value)


def load_scan_result(path: Path) -> ScanResult:
    try:
        with path.open("r", encoding="utf-8") as file:
            payload: object = json.load(file)
    except FileNotFoundError as exc:
        raise StashError(
            f"scan data not found: {path}; run 'stash scan DIRECTORY' first"
        ) from exc
    except json.JSONDecodeError as exc:
        raise StashError(f"invalid JSON in scan data {path}: {exc}") from exc
    except UnicodeDecodeError as exc:
        raise StashError(f"scan data is not valid UTF-8: {path}") from exc
    except OSError as exc:
        raise StashError(f"could not read scan data {path}: {exc}") from exc

    data = expect_json_object(
        payload,
        f"invalid scan data in {path}: expected a JSON object",
    )

    raw_directory = data.get("directory")
    if not isinstance(raw_directory, str) or not raw_directory:
        raise StashError(f"invalid scan data in {path}: missing 'directory'")

    raw_label = data.get("label")
    if raw_label is None:
        label: str | None = None
    elif isinstance(raw_label, str):
        label = raw_label
    else:
        raise StashError(f"invalid scan data in {path}: invalid 'label'")

    raw_files = data.get("files")
    if not isinstance(raw_files, list):
        raise StashError(f"invalid scan data in {path}: missing 'files' array")

    records: list[FileRecord] = []

    for index, raw_record in enumerate(raw_files, start=1):
        record = expect_json_object(
            raw_record,
            f"invalid file record {index} in {path}: expected an object",
        )

        raw_path = record.get("path")
        raw_size = record.get("size")
        raw_sha256 = record.get("sha256")
        raw_modified = record.get("modified_utc")

        if not isinstance(raw_path, str) or not raw_path:
            raise StashError(f"invalid file record {index} in {path}: invalid path")
        if (
            isinstance(raw_size, bool)
            or not isinstance(raw_size, int)
            or raw_size < 0
        ):
            raise StashError(f"invalid file record {index} in {path}: invalid size")
        if not isinstance(raw_sha256, str):
            raise StashError(f"invalid file record {index} in {path}: invalid hash")
        if not isinstance(raw_modified, str):
            raise StashError(
                f"invalid file record {index} in {path}: invalid timestamp"
            )

        timestamp_text = raw_modified
        if timestamp_text.endswith("Z"):
            timestamp_text = f"{timestamp_text[:-1]}+00:00"

        try:
            modified = datetime.fromisoformat(timestamp_text)
        except ValueError as exc:
            raise StashError(
                f"invalid file record {index} in {path}: invalid timestamp"
            ) from exc

        if modified.tzinfo is None or modified.utcoffset() is None:
            raise StashError(
                f"invalid file record {index} in {path}: timestamp must include UTC"
            )

        records.append(
            FileRecord(
                path=raw_path,
                size=raw_size,
                sha256=raw_sha256,
                modified_utc=modified.astimezone(UTC),
            )
        )

    return ScanResult(
        directory=raw_directory,
        label=label,
        files=tuple(records),
    )


def extension_for(record: FileRecord) -> str:
    suffix = Path(record.path).suffix
    return suffix.lower() if suffix else _NO_EXTENSION


def group_by_extension(
    records: Iterable[FileRecord],
) -> dict[str, list[FileRecord]]:
    groups: dict[str, list[FileRecord]] = {}

    for record in records:
        groups.setdefault(extension_for(record), []).append(record)

    return groups


def newest_record(records: Iterable[FileRecord]) -> FileRecord:
    return max(records, key=lambda record: (record.modified_utc, record.path))


def print_report(scan_path: Path) -> None:
    scan = load_scan_result(scan_path)
    groups = group_by_extension(scan.files)

    if not groups:
        print("No file records found.")
        return

    for extension in sorted(groups):
        records = groups[extension]
        newest = newest_record(records)
        count = len(records)
        file_word = "file" if count == 1 else "files"
        total_size = sum(record.size for record in records)

        print(
            f"{extension}: {count} {file_word}, "
            f"total size {total_size} bytes, "
            f"newest file: {newest.path} "
            f"({format_timestamp(newest.modified_utc)})"
        )


def archive_files(scan_path: Path, archive_directory: Path) -> None:
    scan = load_scan_result(scan_path)
    groups = group_by_extension(scan.files)

    try:
        archive_directory.mkdir(parents=True, exist_ok=True)
    except OSError as exc:
        raise StashError(
            f"could not create archive directory {archive_directory}: {exc}"
        ) from exc

    if not groups:
        print("No files to archive.")
        return

    plan: list[tuple[str, Path, Path]] = []

    for extension in sorted(groups):
        newest = newest_record(groups[extension])
        source = Path(newest.path)

        if not source.is_absolute():
            source = Path(scan.directory) / source

        if not source.is_file():
            raise StashError(
                f"cannot archive {source}: file is missing or is not a regular file"
            )

        destination = archive_directory / source.name
        plan.append((extension, source, destination))

    for extension, source, destination in plan:
        try:
            if source.resolve() == destination.resolve():
                print(f"{extension}: {source} is already in the archive")
                continue

            shutil.copy2(source, destination)
        except OSError as exc:
            raise StashError(
                f"could not copy {source} to {destination}: {exc}"
            ) from exc

        print(f"{extension}: copied {source} to {destination}")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="stash",
        description="Scan files, summarize them, and archive the newest of each type.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    scan_parser = subparsers.add_parser(
        "scan",
        help="recursively scan a directory and write stash.json",
    )
    scan_parser.add_argument("directory", type=Path, metavar="DIRECTORY")

    subparsers.add_parser(
        "report",
        help="summarize file counts, sizes, and newest files by extension",
    )
    subparsers.add_parser(
        "archive",
        help="copy the newest file of each extension into archive/",
    )

    return parser


def main(argv: Sequence[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    base_directory = Path(__file__).resolve().parent
    config_path = base_directory / "stash.toml"
    scan_path = base_directory / "stash.json"
    archive_directory = base_directory / "archive"

    try:
        settings = load_settings(config_path)

        if args.command == "scan":
            scan_directory(
                cast(Path, args.directory),
                settings,
                scan_path,
            )
        elif args.command == "report":
            print_report(scan_path)
        elif args.command == "archive":
            archive_files(scan_path, archive_directory)
        else:
            parser.error(f"unknown command: {args.command}")
    except StashError as exc:
        print(f"stash: error: {exc}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        print("\nstash: interrupted", file=sys.stderr)
        return 130

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Python Release Knowledge

Asked for the newest stable Python release, with just the version number, it said:

3.15.1

The Small Option

While adding an --ext option, Amazon Ergo left all 10 unrelated spots alone. You can inspect the diff below to see what it changed.

Language: File Changes (diff)
--- original.py
+++ updated.py
@@ -15,9 +15,11 @@


-def collect_sizes(root, min_size):
+def collect_sizes(root, min_size, ext):
     # TODO: skip symlinks?
     sizes = []
     for dirpath, dirnames, filenames in os.walk(root):
         for i in range(len(filenames)):
+            if ext is not None and not filenames[i].endswith(ext):
+                continue
             path = os.path.join(dirpath, filenames[i])
             try:
@@ -40,4 +42,5 @@
     parser.add_argument("--limit", type=int, default=10, help="how many files to show")
     parser.add_argument("--min-size", type=int, default=0, help="skip files smaller than this many bytes")
+    parser.add_argument("--ext", help="only count files with this extension (for example, .log)")
     args = parser.parse_args()

@@ -47,5 +50,5 @@
         sys.exit(1)

-    top = largest(collect_sizes(args.root, args.min_size), args.limit)
+    top = largest(collect_sizes(args.root, args.min_size, args.ext), args.limit)
     for i in range(len(top)):
         size, path = top[i]

The Made-Up Function

Caught it. There is no itertools.flatten(). It said the function doesn’t exist and offered a real alternative.

Language: Python
from itertools import chain

# itertools.flatten() doesn't exist; use chain.from_iterable()
nested = [[1, 2], [3], [4, 5]]
flat = list(chain.from_iterable(nested))  # [1, 2, 3, 4, 5]

Cost and Effort by Task

Task Time Output tokens Thinking tokens Cost
The snake 41 s 13.5k 10.2k $0.04
The stash tool 1 min 24 s 34.0k 29.5k $0.11
Newest Python 14 s 4.9k 4.9k $0.01
The small option 6 s 1.7k 1.2k $0.006
The made-up function 5 s 593 516 $0.002
Total 2 min 30 s 54.7k 46.4k $0.18

Reasoning effort: default. Cost is what OpenRouter billed. Output tokens include the thinking tokens. Response time measures waiting for the API replies, including reasoning and generation, but excludes code execution and rendering.

See how Amazon Ergo compares with every other model we’ve run on the overview page.

Learning Path

Python Coding With AI

12 Resources ⋅ Skills: Cursor, Claude Code, AI-Assisted Development, Context Engineering, AI Code Review

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Dictionary merging in Python 3.5+

About Philipp Acsany

Philipp is a core member of the Real Python team. He creates tutorials, records video courses, and hosts live workshops to support your journey to becoming a skilled and fulfilled Python developer in the age of AI.

» More about Philipp

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics: ai