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.

Step 5 Draws a Python Reading a Book

by Philipp Acsany Updated Reading time estimate 20m ai

We asked Step 5 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 Step 5.
Turtle animation of Step 5 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 Script error 0 drawing commands, 253 lines of code. Error: AttributeError: 'Turtle' object has no attribute 'tracer'
How modern its Python is Python 3.10 (2021) pinned by file_digest. Newest feature used: Python 3.11
Modern idioms 7 of 12 of the checkpoints that applied to its code
Latest Python version reported 3.13.0 the reply is quoted below
Unrelated edits 1 of 10 changed range(len) loops
Spots a made-up function? Caught it said the function doesn’t exist and offered a real alternative
Reasoning effort default 49.4k thinking tokens over all five tasks
Cost $0.15 for all 5 tasks, as billed by the API
Response time 6 min 44 s 56.3k output tokens

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

The Five Tasks

The Snake

The script stopped before it finished. The recorded drawing shows its progress up to that point. 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

screen = turtle.Screen()
screen.setup(1000, 700)
screen.bgcolor("#f7f3e8")
screen.title("A Python Reading a Book")

pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.tracer(0, 0)


def ellipse(cx, cy, rx, ry, angle=0, fill="#000000", outline=None, width=1):
    """Draw a filled ellipse, optionally rotated."""
    outline = outline or fill
    rad = math.radians(angle)
    points = []

    for i in range(73):
        a = 2 * math.pi * i / 72
        x = rx * math.cos(a)
        y = ry * math.sin(a)

        X = cx + x * math.cos(rad) - y * math.sin(rad)
        Y = cy + x * math.sin(rad) + y * math.cos(rad)
        points.append((X, Y))

    pen.penup()
    pen.goto(points[0])
    pen.pendown()
    pen.fillcolor(fill)
    pen.pencolor(outline)
    pen.width(width)
    pen.begin_fill()

    for point in points[1:]:
        pen.goto(point)

    pen.goto(points[0])
    pen.end_fill()
    pen.penup()


def polygon(points, fill, outline=None, width=1):
    """Draw a filled polygon."""
    outline = outline or fill

    pen.penup()
    pen.goto(points[0])
    pen.pendown()
    pen.fillcolor(fill)
    pen.pencolor(outline)
    pen.width(width)
    pen.begin_fill()

    for point in points[1:]:
        pen.goto(point)

    pen.goto(points[0])
    pen.end_fill()
    pen.penup()


def line(points, color, width=2):
    """Draw a line through a list of points."""
    pen.penup()
    pen.goto(points[0])
    pen.pendown()
    pen.pencolor(color)
    pen.width(width)

    for point in points[1:]:
        pen.goto(point)

    pen.penup()


def thick_path(points, color, width):
    """Draw a thick path with rounded joints."""
    line(points, color, width)

    radius = width / 2
    for x, y in points:
        ellipse(x, y, radius, radius, 0, color, color, 1)


def circle_outline(x, y, radius, color, width=2):
    """Draw an outlined circle centered at (x, y)."""
    pen.penup()
    pen.goto(x, y - radius)
    pen.setheading(0)
    pen.pendown()
    pen.pencolor(color)
    pen.width(width)
    pen.circle(radius)
    pen.penup()


# Colors
BODY = "#5b9e4a"
BODY_DARK = "#2f6b2b"
BODY_LIGHT = "#7fb86a"
BOOK_COVER = "#8b3a3a"
BOOK_COVER_DARK = "#5e2424"
PAGE = "#fff8e7"
PAGE_LINE = "#c9bfa8"
INK = "#4a3b2a"

# Title
pen.penup()
pen.goto(0, 300)
pen.pencolor(INK)
pen.write(
    "A Python Reading a Book",
    align="center",
    font=("Arial", 24, "bold")
)
pen.penup()

# Ground shadow
ellipse(0, -265, 430, 30, 0, "#e6dfcf", "#e6dfcf", 1)

# Snake body: a coiled path rising behind the head
body_points = [
    (-350, -200), (-400, -150), (-410, -60), (-370, 10),
    (-280, 35), (-160, 20), (-30, -10), (110, -15),
    (230, 10), (310, -40), (340, -130), (300, -210),
    (210, -250), (90, -260), (-40, -250), (-170, -230),
    (-260, -190), (-300, -130), (-290, -70), (-230, -20),
    (-130, 5), (-20, 0), (90, -10), (190, 10),
    (260, 50), (300, 110), (290, 170), (240, 210),
    (170, 225), (90, 215), (30, 190), (0, 150)
]

thick_path(body_points, BODY, 46)

# Tail tip
polygon(
    [(-350, -200), (-420, -210), (-390, -175), (-360, -180)],
    BODY,
    BODY_DARK,
    2
)

# Spots on the snake
spots = [
    (-360, -120, 8), (-320, 0, 7), (-220, 20, 8), (-80, -5, 7),
    (100, -10, 8), (250, -20, 7), (320, -110, 8), (280, -200, 7),
    (170, -240, 8), (20, -250, 7), (-150, -225, 8), (-270, -170, 7),
    (-290, -80, 8), (-200, -10, 7), (-20, 5, 8), (180, 20, 7),
    (280, 100, 8), (260, 180, 7), (150, 215, 8), (40, 190, 7)
]

for x, y, radius in spots:
    ellipse(x, y, radius, radius, 0, BODY_DARK, BODY_DARK, 1)

# Head
ellipse(0, 115, 42, 55, 0, BODY, BODY_DARK, 3)

# Snout highlight
ellipse(0, 88, 24, 18, 0, BODY_LIGHT, BODY_LIGHT, 1)

# Eyes
ellipse(-18, 130, 10, 12, 0, "#ffffff", BODY_DARK, 2)
ellipse(18, 130, 10, 12, 0, "#ffffff", BODY_DARK, 2)

# Pupils looking down at the book
ellipse(-18, 126, 4, 6, 0, "#1b1b1b", "#1b1b1b", 1)
ellipse(18, 126, 4, 6, 0, "#1b1b1b", "#1b1b1b", 1)

# Eye shines
ellipse(-19, 128, 1.5, 1.5, 0, "#ffffff", "#ffffff", 1)
ellipse(17, 128, 1.5, 1.5, 0, "#ffffff", "#ffffff", 1)

# Nostrils
ellipse(-8, 82, 2.5, 2.5, 0, BODY_DARK, BODY_DARK, 1)
ellipse(8, 82, 2.5, 2.5, 0, BODY_DARK, BODY_DARK, 1)

# Mouth
line(
    [(-14, 96), (-7, 92), (0, 91), (7, 92), (14, 96)],
    BODY_DARK,
    2
)

# Reading glasses
circle_outline(-18, 130, 16, INK, 2)
circle_outline(18, 130, 16, INK, 2)
line([(-2, 130), (2, 130)], INK, 2)
line([(-34, 130), (-42, 124)], INK, 2)
line([(34, 130), (42, 124)], INK, 2)

# Book covers
polygon(
    [(0, -180), (-195, -150), (-205, -30), (0, -60)],
    BOOK_COVER,
    BOOK_COVER_DARK,
    3
)
polygon(
    [(0, -180), (195, -150), (205, -30), (0, -60)],
    BOOK_COVER,
    BOOK_COVER_DARK,
    3
)

# Book pages
polygon(
    [(0, -168), (-183, -140), (-192, -38), (0, -68)],
    PAGE,
    "#d8cdb5",
    2
)
polygon(
    [(0, -168), (183, -140), (192, -38), (0, -68)],
    PAGE,
    "#d8cdb5",
    2
)

# Lines representing text on the pages
left_lines = [
    [(-18, -82), (-165, -58)],
    [(-18, -100), (-168, -76)],
    [(-18, -118), (-170, -94)],
    [(-18, -136), (-165, -112)],
]

right_lines = [
    [(-x, y) for x, y in points]
    for points in left_lines
]

for points in left_lines + right_lines:
    line(points, PAGE_LINE, 2)

# Book spine
line([(0, -66), (0, -170)], "#b5a88e", 2)

# Bookmark ribbon
polygon(
    [(0, -176), (10, -176), (10, -218), (5, -228), (0, -218)],
    "#c94f4f",
    "#8b2f2f",
    1
)

# Finish drawing
pen.hideturtle()
screen.update()
turtle.done()

The Stash Tool

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

Its code used 7 of the 12 newer Python features checked by our rubric. For example, it used a manual hashing loop instead of hashlib.file_digest() (Python 3.11) and os.walk() instead of Path.walk() (Python 3.12). These choices give it a Python 3.10 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 datetime.UTC, 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 ❌ stale 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
"""stash: scan, report, and archive files.

Configuration is read from stash.toml next to this script:

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

from __future__ import annotations

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

SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = SCRIPT_DIR / "stash.toml"
STASH_PATH = SCRIPT_DIR / "stash.json"
ARCHIVE_DIR = SCRIPT_DIR / "archive"
HASH_CHUNK_SIZE = 1024 * 1024


class StashError(Exception):
    """A user-facing stash error."""


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


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


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


@dataclass(slots=True)
class ExtensionSummary:
    extension: str
    count: int
    total_size: int
    newest: FileRecord


def _load_config() -> Config:
    if not CONFIG_PATH.exists():
        raise StashError(f"configuration file not found: {CONFIG_PATH}")
    if not CONFIG_PATH.is_file():
        raise StashError(f"configuration path is not a file: {CONFIG_PATH}")

    try:
        with CONFIG_PATH.open("rb") as handle:
            raw: dict[str, object] = tomllib.load(handle)
    except tomllib.TOMLDecodeError as exc:
        raise StashError(f"invalid TOML in {CONFIG_PATH}: {exc}") from exc
    except UnicodeError as exc:
        raise StashError(f"invalid text in {CONFIG_PATH}: {exc}") from exc
    except OSError as exc:
        raise StashError(f"could not read configuration file {CONFIG_PATH}: {exc}") from exc

    ignore_value = raw.get("ignore", raw.get("ignore_patterns", []))
    if not isinstance(ignore_value, list) or not all(
        isinstance(item, str) for item in ignore_value
    ):
        raise StashError("stash.toml: 'ignore' must be an array of strings")

    batch_value = raw.get("batch_size", raw.get("batch"))
    if (
        not isinstance(batch_value, int)
        or isinstance(batch_value, bool)
        or batch_value <= 0
    ):
        raise StashError("stash.toml: 'batch_size' must be a positive integer")

    label_value = raw.get("label")
    if label_value is not None and not isinstance(label_value, str):
        raise StashError("stash.toml: 'label' must be a string")

    return Config(
        ignore_patterns=tuple(cast(list[str], ignore_value)),
        batch_size=batch_value,
        label=label_value,
    )


def _matches_ignore(
    relative_path: Path,
    patterns: Sequence[str],
    *,
    is_directory: bool = False,
) -> bool:
    rel = relative_path.as_posix()
    parts = relative_path.parts
    candidates: list[str] = [rel, relative_path.name]
    candidates.extend(parts[:-1])
    candidates.extend("/".join(parts[:index]) for index in range(1, len(parts)))
    if is_directory:
        candidates.append(rel + "/")

    for pattern in patterns:
        normalized = pattern.replace("\\", "/").strip()
        if normalized.startswith("./"):
            normalized = normalized[2:]
        if normalized.startswith("/"):
            normalized = normalized.lstrip("/")
        if not normalized:
            continue

        if normalized.endswith("/"):
            directory_pattern = normalized.rstrip("/")
            if directory_pattern and (
                rel == directory_pattern or rel.startswith(directory_pattern + "/")
            ):
                return True

        if any(
            fnmatch.fnmatchcase(candidate, normalized) for candidate in candidates
        ):
            return True

        if normalized.startswith("**/") and fnmatch.fnmatchcase(
            rel, normalized[3:]
        ):
            return True

    return False


def _walk_error(error: OSError) -> None:
    raise StashError(f"could not walk directory: {error}")


def _collect_files(root: Path, patterns: Sequence[str]) -> list[Path]:
    files: list[Path] = []

    for dirpath, dirnames, filenames in os.walk(root, onerror=_walk_error):
        current = Path(dirpath)

        kept_dirs: list[str] = []
        for dirname in sorted(dirnames):
            child = current / dirname
            relative = child.relative_to(root)
            if not _matches_ignore(relative, patterns, is_directory=True):
                kept_dirs.append(dirname)
        dirnames[:] = kept_dirs

        for filename in sorted(filenames):
            path = current / filename
            try:
                file_stat = path.stat()
            except FileNotFoundError:
                continue
            except OSError as exc:
                raise StashError(f"could not inspect {path}: {exc}") from exc

            if not stat.S_ISREG(file_stat.st_mode):
                continue

            relative = path.relative_to(root)
            if _matches_ignore(relative, patterns):
                continue

            files.append(path)

    return files


def _validate_directory(path: Path) -> Path:
    try:
        resolved = path.expanduser().resolve(strict=True)
    except FileNotFoundError as exc:
        raise StashError(f"directory not found: {path}") from exc
    except OSError as exc:
        raise StashError(f"could not access directory {path}: {exc}") from exc
    except RuntimeError as exc:
        raise StashError(f"could not resolve directory {path}: {exc}") from exc

    if not resolved.is_dir():
        raise StashError(f"not a directory: {path}")
    return resolved


def _utc_timestamp(timestamp: float) -> str:
    value = datetime.fromtimestamp(timestamp, tz=UTC)
    return value.isoformat(timespec="microseconds").replace("+00:00", "Z")


def _hash_file(path: Path) -> tuple[int, str, str]:
    try:
        file_stat = path.stat()
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            while chunk := handle.read(HASH_CHUNK_SIZE):
                digest.update(chunk)
    except OSError as exc:
        raise StashError(f"could not read file {path}: {exc}") from exc

    return (
        file_stat.st_size,
        digest.hexdigest(),
        _utc_timestamp(file_stat.st_mtime),
    )


def _write_stash(data: StashData) -> None:
    payload: dict[str, object] = {
        "version": 1,
        "label": data.label,
        "directory": data.directory.as_posix(),
        "files": [
            {
                "path": record.path.as_posix(),
                "size": record.size,
                "sha256": record.sha256,
                "mtime_utc": record.mtime_utc,
            }
            for record in data.files
        ],
    }

    temp_name: str | None = None
    try:
        with tempfile.NamedTemporaryFile(
            mode="w",
            encoding="utf-8",
            dir=SCRIPT_DIR,
            prefix=".stash-",
            suffix=".json.tmp",
            delete=False,
        ) as handle:
            temp_name = handle.name
            json.dump(payload, handle, indent=2, sort_keys=True)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())

        if temp_name is None:
            raise StashError(f"could not write {STASH_PATH}: no temporary file created")
        os.replace(temp_name, STASH_PATH)
    except OSError as exc:
        if temp_name is not None:
            try:
                Path(temp_name).unlink(missing_ok=True)
            except OSError:
                pass
        raise StashError(f"could not write {STASH_PATH}: {exc}") from exc


def _require_str(mapping: Mapping[str, object], key: str, context: str) -> str:
    value = mapping.get(key)
    if not isinstance(value, str):
        raise StashError(
            f"invalid stash file {STASH_PATH}: {context}.{key} must be a string"
        )
    return value


def _require_nonnegative_int(
    mapping: Mapping[str, object],
    key: str,
    context: str,
) -> int:
    value = mapping.get(key)
    if not isinstance(value, int) or isinstance(value, bool) or value < 0:
        raise StashError(
            f"invalid stash file {STASH_PATH}: "
            f"{context}.{key} must be a non-negative integer"
        )
    return value


def _read_stash() -> StashData:
    if not STASH_PATH.exists():
        raise StashError(
            f"stash file not found: {STASH_PATH}; "
            "run 'stash scan DIRECTORY' first"
        )
    if not STASH_PATH.is_file():
        raise StashError(f"stash path is not a file: {STASH_PATH}")

    try:
        with STASH_PATH.open("r", encoding="utf-8") as handle:
            raw_obj: object = json.load(handle)
    except json.JSONDecodeError as exc:
        raise StashError(f"invalid JSON in {STASH_PATH}: {exc}") from exc
    except UnicodeError as exc:
        raise StashError(f"invalid text in {STASH_PATH}: {exc}") from exc
    except OSError as exc:
        raise StashError(f"could not read {STASH_PATH}: {exc}") from exc

    if not isinstance(raw_obj, dict):
        raise StashError(f"invalid stash file {STASH_PATH}: expected a JSON object")

    raw = cast(dict[str, object], raw_obj)
    version = raw.get("version", 1)
    if (
        not isinstance(version, int)
        or isinstance(version, bool)
        or version != 1
    ):
        raise StashError(f"unsupported stash file version: {version!r}")

    label_value = raw.get("label")
    if label_value is not None and not isinstance(label_value, str):
        raise StashError(
            f"invalid stash file {STASH_PATH}: 'label' must be a string or null"
        )

    directory = Path(_require_str(raw, "directory", "stash"))
    files_raw = raw.get("files")
    if not isinstance(files_raw, list):
        raise StashError(f"invalid stash file {STASH_PATH}: 'files' must be an array")

    records: list[FileRecord] = []
    for index, item in enumerate(files_raw):
        item_obj: object = item
        if not isinstance(item_obj, dict):
            raise StashError(
                f"invalid stash file {STASH_PATH}: files[{index}] must be an object"
            )

        item_map = cast(dict[str, object], item_obj)
        context = f"files[{index}]"
        records.append(
            FileRecord(
                path=Path(_require_str(item_map, "path", context)),
                size=_require_nonnegative_int(item_map, "size", context),
                sha256=_require_str(item_map, "sha256", context),
                mtime_utc=_require_str(item_map, "mtime_utc", context),
            )
        )

    return StashData(
        label=label_value,
        directory=directory,
        files=tuple(records),
    )


def _parse_mtime(value: str) -> datetime:
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError as exc:
        raise StashError(f"invalid UTC timestamp in stash file: {value!r}") from exc

    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=UTC)
    return parsed.astimezone(UTC)


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

    for record in records:
        extension = record.path.suffix.lower() or "(no extension)"
        summary = groups.get(extension)
        if summary is None:
            groups[extension] = ExtensionSummary(
                extension=extension,
                count=1,
                total_size=record.size,
                newest=record,
            )
            continue

        summary.count += 1
        summary.total_size += record.size

        candidate_key = (
            _parse_mtime(record.mtime_utc),
            record.path.as_posix(),
        )
        newest_key = (
            _parse_mtime(summary.newest.mtime_utc),
            summary.newest.path.as_posix(),
        )
        if candidate_key > newest_key:
            summary.newest = record

    return groups


def _scan(directory: Path, config: Config) -> None:
    root = _validate_directory(directory)
    files = _collect_files(root, config.ignore_patterns)
    records: list[FileRecord] = []
    total = len(files)

    if total == 0:
        print("No files to hash.")

    batch_number = 0
    for start in range(0, total, config.batch_size):
        batch_number += 1
        batch = files[start : start + config.batch_size]

        for path in batch:
            size, sha256, mtime_utc = _hash_file(path)
            records.append(
                FileRecord(
                    path=path,
                    size=size,
                    sha256=sha256,
                    mtime_utc=mtime_utc,
                )
            )

        done = start + len(batch)
        print(f"Batch {batch_number}: hashed {done}/{total} files")

    data = StashData(
        label=config.label,
        directory=root,
        files=tuple(records),
    )
    _write_stash(data)
    print(f"Wrote {STASH_PATH}")


def _report() -> None:
    data = _read_stash()
    groups = _group_newest(data.files)

    print(f"Stash report: {data.label}" if data.label else "Stash report")
    if not groups:
        print("No files in stash.")
        return

    for extension in sorted(groups):
        summary = groups[extension]
        newest = summary.newest
        file_word = "file" if summary.count == 1 else "files"
        print(
            f"{extension}: {summary.count} {file_word}, "
            f"{summary.total_size} bytes, "
            f"newest: {newest.path.as_posix()} ({newest.mtime_utc})"
        )


def _archive() -> None:
    data = _read_stash()
    groups = _group_newest(data.files)

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

    if not ARCHIVE_DIR.is_dir():
        raise StashError(f"archive path is not a directory: {ARCHIVE_DIR}")

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

    selected: list[tuple[str, Path, Path]] = []
    for extension in sorted(groups):
        record = groups[extension].newest
        source = record.path
        if not source.is_absolute():
            source = data.directory / source

        destination = ARCHIVE_DIR / source.name
        if not source.is_file():
            raise StashError(f"cannot archive missing file: {source}")
        if destination.exists() and destination.is_dir():
            raise StashError(f"archive destination is a directory: {destination}")

        selected.append((extension, source, destination))

    for extension, source, destination in selected:
        try:
            shutil.copy2(source, destination)
        except shutil.SameFileError:
            pass
        except OSError as exc:
            raise StashError(
                f"could not copy {source} to {destination}: {exc}"
            ) from exc

        print(f"Archived {extension}: {source} -> {destination}")


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="stash",
        description="Scan, report, and archive files.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

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

    subparsers.add_parser(
        "report",
        help="print a per-extension summary from stash.json",
    )
    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: argparse.Namespace = parser.parse_args(argv)

    try:
        config = _load_config()

        if args.command == "scan":
            _scan(args.directory, config)
        elif args.command == "report":
            _report()
        elif args.command == "archive":
            _archive()
        else:
            raise StashError(f"unknown command: {args.command}")
    except StashError as exc:
        print(f"stash: error: {exc}", file=sys.stderr)
        return 1
    except OSError as exc:
        print(f"stash: error: {exc}", file=sys.stderr)
        return 1

    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.13.0

The Small Option

While adding an --ext option, Step 5 also changed 1 of the 10 unrelated spots we planted: range(len) loops. You can inspect the diff below to see what it changed.

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


-def collect_sizes(root, min_size):
+def collect_sizes(root, min_size, extension=None):
     # TODO: skip symlinks?
     sizes = []
     for dirpath, dirnames, filenames in os.walk(root):
-        for i in range(len(filenames)):
-            path = os.path.join(dirpath, filenames[i])
+        for filename in filenames:
+            if extension is not None and os.path.splitext(filename)[1] != extension:
+                continue
+            path = os.path.join(dirpath, filename)
             try:
                 size = os.path.getsize(path)
@@ -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", metavar=".EXT", help="only count files with this extension (e.g. .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.

itertools.flatten() isn’t in the standard library. Use chain.from_iterable:

Language: Python
from itertools import chain

flat = list(chain.from_iterable(list_of_lists))

Cost and Effort by Task

Task Time Output tokens Thinking tokens Cost
The snake 1 min 30 s 12.0k 9.7k $0.03
The stash tool 4 min 25 s 38.3k 34.2k $0.10
Newest Python 30 s 3.6k 3.6k $0.010
The small option 16 s 2.1k 1.7k $0.006
The made-up function 3 s 228 183 $0.001
Total 6 min 44 s 56.3k 49.4k $0.15

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 Step 5 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