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.

Hy4 flash Draws a Python Reading a Book

by Philipp Acsany Updated Reading time estimate 22m ai

We asked Hy4 flash 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 Hy4 flash.
Turtle animation of Hy4 flash 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 1189 drawing commands, 276 lines of code
How modern its Python is Python 3.10 (2021) pinned by datetime_utc. Newest feature used: Python 3.11
Modern idioms 6 of 14 of the checkpoints that applied to its code
Latest Python version reported 3.13 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 39.2k thinking tokens over all five tasks
Cost $0.007 for all 5 tasks, as billed by the API
Response time 4 min 24 s 47.0k output tokens

The run: tencent/hy4-flash 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

# Colors
BG = "#fff9e8"
DARK = "#173f2a"
GREEN = "#58a64b"
LIGHT = "#91d16b"
SPOT = "#2d7340"
PAGE = "#fffdf0"
BOOK = "#7d3434"
INK = "#5b5146"


# ---------- Drawing helpers ----------

def draw_dot(t, x, y, size, color):
    t.penup()
    t.goto(x, y)
    t.dot(max(1, int(size)), color)


def draw_line(t, p1, p2, color, width=2):
    t.penup()
    t.goto(p1)
    t.pendown()
    t.pencolor(color)
    t.pensize(width)
    t.goto(p2)
    t.penup()


def bezier(p0, p1, p2, n=24):
    pts = []
    for i in range(n + 1):
        u = i / n
        v = 1 - u
        x = v * v * p0[0] + 2 * v * u * p1[0] + u * u * p2[0]
        y = v * v * p0[1] + 2 * v * u * p1[1] + u * u * p2[1]
        pts.append((x, y))
    return pts


def curves_to_points(curves, n=24):
    pts = []
    for curve in curves:
        seg = bezier(*curve, n)
        if pts:
            seg = seg[1:]
        pts.extend(seg)
    return pts


def mirror_points(points):
    return [(-x, y) for x, y in points]


def mirror_curves(curves):
    return [tuple((-x, y) for x, y in p) for p in curves]


def draw_shape(t, points, fill=None, outline=INK, width=2):
    if not points:
        return

    t.penup()
    t.goto(points[0])
    t.pendown()

    t.pencolor(outline if outline is not None else fill if fill else INK)
    t.pensize(width)

    if fill:
        t.fillcolor(fill)
        t.begin_fill()

    for p in points[1:]:
        t.goto(p)

    t.goto(points[0])

    if fill:
        t.end_fill()

    t.penup()


def draw_open_curve(t, curves, color, width=2, n=24):
    pts = curves_to_points(curves, n)
    t.penup()
    t.goto(pts[0])
    t.pendown()
    t.pencolor(color)
    t.pensize(width)

    for p in pts[1:]:
        t.goto(p)

    t.penup()


def draw_ellipse(t, cx, cy, rx, ry, fill=None, outline=INK,
                 rotation=0, width=2, steps=72):
    a = math.radians(rotation)
    ca, sa = math.cos(a), math.sin(a)
    pts = []

    for i in range(steps):
        theta = 2 * math.pi * i / steps
        x = rx * math.cos(theta)
        y = ry * math.sin(theta)
        xr = x * ca - y * sa
        yr = x * sa + y * ca
        pts.append((cx + xr, cy + yr))

    draw_shape(t, pts, fill, outline, width)


# ---------- Scene parts ----------

def draw_background(t):
    # Soft shadow
    draw_ellipse(t, 0, -277, 370, 30, "#e8dec0", "#e8dec0", 0, 1)

    # Ground line and grass
    draw_line(t, (-410, -290), (410, -290), "#a9c98e", 3)

    for x in range(-390, 391, 45):
        draw_line(t, (x, -290), (x + 8, -278), "#7dac6b", 2)
        draw_line(t, (x + 8, -290), (x + 14, -282), "#7dac6b", 2)


def draw_body(t):
    # Curved body path, from tail to head
    body = [
        (-320, -230), (-270, -252), (-215, -268), (-155, -273),
        (-95, -268), (-35, -252), (25, -230), (80, -200),
        (130, -163), (170, -118), (190, -68), (186, -15),
        (160, 25), (120, 48), (70, 56), (20, 45),
        (-25, 20), (-55, -20), (-62, -70), (-45, -120),
        (-5, -155), (45, -166), (92, -142), (112, -100),
        (100, -55), (65, -22), (25, 0), (8, 30), (0, 58)
    ]

    # Draw thick outline and green body segments
    for i in range(len(body) - 1):
        w = min(42, 12 + 2 * i)
        draw_line(t, body[i], body[i + 1], DARK, w + 6)
        draw_line(t, body[i], body[i + 1], GREEN, w)

    # Round joints so the body looks smooth
    for i, p in enumerate(body):
        w = min(42, 12 + 2 * i)
        draw_dot(t, p[0], p[1], w + 6, DARK)
        draw_dot(t, p[0], p[1], w, GREEN)

    # Python spots
    spots = [
        (2, 8), (4, 9), (7, 11), (10, 11),
        (12, 10), (14, 9), (16, 9), (19, 10), (22, 10)
    ]

    for idx, size in spots:
        x, y = body[idx]
        draw_dot(t, x, y, size, SPOT)


def draw_book(t):
    # Book cover, right half
    right_cover = [
        ((0, -48), (100, -30), (205, -50)),
        ((205, -50), (220, -120), (207, -198)),
        ((207, -198), (100, -178), (0, -205)),
        ((0, -205), (0, -125), (0, -48))
    ]

    draw_shape(t, curves_to_points(mirror_curves(right_cover)), BOOK, "#562626", 3)
    draw_shape(t, curves_to_points(right_cover), BOOK, "#562626", 3)

    # Bookmark ribbon, tucked under the pages
    draw_shape(
        t,
        [(16, -185), (36, -185), (31, -247), (26, -231), (21, -247)],
        "#b53b4f",
        "#7e2437",
        2
    )

    # Open pages
    right_pages = [
        ((0, -62), (90, -43), (180, -56)),
        ((180, -56), (200, -112), (182, -180)),
        ((182, -180), (90, -166), (0, -188)),
        ((0, -188), (0, -126), (0, -62))
    ]

    draw_shape(t, curves_to_points(mirror_curves(right_pages)), PAGE, "#d7cbb1", 2)
    draw_shape(t, curves_to_points(right_pages), PAGE, "#d7cbb1", 2)

    # Page lines
    for y in [-84, -104, -124, -144, -164]:
        draw_line(t, (30, y), (158, y + 8), "#bcb09a", 2)
        draw_line(t, (-30, y), (-158, y + 8), "#bcb09a", 2)

    # Book title
    t.penup()
    t.goto(-150, -96)
    t.pencolor("#2e6a50")
    t.write("Python", font=("Arial", 16, "bold"))
    t.penup()

    # Spine
    draw_line(t, (0, -60), (0, -191), "#756855", 3)


def draw_head(t):
    # Head and snout
    draw_ellipse(t, 0, 65, 72, 48, GREEN, DARK, rotation=-4, width=3)
    draw_ellipse(t, 0, 37, 49, 29, LIGHT, "#3d8d40", rotation=0, width=2)

    # Eyes
    draw_dot(t, -29, 76, 30, "white")
    draw_dot(t, 29, 76, 30, "white")

    # Pupils looking down toward the book
    draw_dot(t, -26, 71, 13, DARK)
    draw_dot(t, 26, 71, 13, DARK)

    # Eye sparkles
    draw_dot(t, -28, 74, 4, "white")
    draw_dot(t, 24, 74, 4, "white")

    # Glasses
    draw_ellipse(t, -29, 76, 24, 23, None, "#5f87a3", 0, 3, 48)
    draw_ellipse(t, 29, 76, 24, 23, None, "#5f87a3", 0, 3, 48)
    draw_line(t, (-5, 76), (5, 76), "#5f87a3", 3)
    draw_line(t, (-53, 77), (-69, 72), "#5f87a3", 3)
    draw_line(t, (53, 77), (69, 72), "#5f87a3", 3)

    # Nostrils
    draw_dot(t, -9, 42, 5, DARK)
    draw_dot(t, 9, 42, 5, DARK)

    # Smile
    draw_open_curve(
        t,
        [((-17, 30), (0, 18), (17, 30))],
        DARK,
        2,
        24
    )


def main():
    screen = turtle.Screen()
    screen.setup(900, 650)
    screen.bgcolor(BG)
    screen.title("A Python Reading a Book")

    t = turtle.Turtle()
    t.hideturtle()
    t.speed(0)

    screen.tracer(0)

    draw_background(t)
    draw_body(t)
    draw_book(t)
    draw_head(t)

    screen.update()
    screen.mainloop()


if __name__ == "__main__":
    main()

The Stash Tool

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

Its code used 6 of the 14 newer Python features checked by our rubric. For example, it used timezone.utc, utcnow(), utcfromtimestamp() instead of datetime.UTC (Python 3.11) and a manual hashing loop instead of hashlib.file_digest() (Python 3.11). 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 import tomllib, 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 ❌ stale 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 ❌ stale 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 ❌ stale -> 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 described by stash.json."""

from __future__ import annotations

import argparse
import fnmatch
import hashlib
import json
import os
import shutil
import sys
from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Any

if sys.version_info < (3, 11):
    print("stash: error: Python 3.11 or newer is required", file=sys.stderr)
    raise SystemExit(1)

import tomllib

SCRIPT_DIR: Path = Path(__file__).resolve().parent
CONFIG_PATH: Path = SCRIPT_DIR / "stash.toml"
STASH_PATH: Path = SCRIPT_DIR / "stash.json"
ARCHIVE_DIR: Path = SCRIPT_DIR / "archive"
CHUNK_SIZE: int = 1024 * 1024
NO_EXTENSION: str = "(no extension)"
STASH_VERSION: int = 1
_HEX_DIGITS: str = "0123456789abcdefABCDEF"


class StashError(Exception):
    """Raised for user-facing stash errors."""


@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: str
    size_bytes: int
    sha256: str
    modified_utc: str

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

    @classmethod
    def from_dict(cls, value: Any, *, index: int) -> FileRecord:
        context = f"stash.json files[{index}]"
        if not isinstance(value, dict):
            raise StashError(f"{context} must be an object")

        data: dict[str, Any] = value
        path = require_string(data.get("path"), "path", context)
        if not path:
            raise StashError(f"{context}: 'path' must not be empty")

        size_bytes = data.get("size_bytes")
        if isinstance(size_bytes, bool) or not isinstance(size_bytes, int) or size_bytes < 0:
            raise StashError(f"{context}: 'size_bytes' must be a non-negative integer")

        sha256 = require_string(data.get("sha256"), "sha256", context)
        if len(sha256) != 64 or any(char not in _HEX_DIGITS for char in sha256):
            raise StashError(f"{context}: 'sha256' must be a 64-character hexadecimal string")

        modified_utc = require_string(data.get("modified_utc"), "modified_utc", context)
        return cls(
            path=path,
            size_bytes=size_bytes,
            sha256=sha256,
            modified_utc=modified_utc,
        )

    def extension(self) -> str:
        suffix = Path(self.path).suffix.lower()
        return suffix or NO_EXTENSION

    def modified_datetime(self) -> datetime:
        value = self.modified_utc
        if value.endswith("Z"):
            value = value[:-1] + "+00:00"
        try:
            parsed = datetime.fromisoformat(value)
        except ValueError as exc:
            raise StashError(
                f"Invalid modified_utc timestamp for {self.path!r}: {self.modified_utc!r}"
            ) from exc
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=timezone.utc)
        return parsed.astimezone(timezone.utc)


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

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

    @classmethod
    def from_dict(cls, value: Any) -> StashData:
        if not isinstance(value, dict):
            raise StashError("stash.json must contain a JSON object")

        data: dict[str, Any] = value
        version = data.get("version")
        if isinstance(version, bool) or version != STASH_VERSION:
            raise StashError(
                f"Unsupported stash.json version: {version!r}; expected {STASH_VERSION}"
            )

        root = require_string(data.get("root"), "root", "stash.json")
        if not root:
            raise StashError("stash.json: 'root' must not be empty")

        label = require_optional_string(data.get("label"), "label", "stash.json")

        files_value = data.get("files")
        if not isinstance(files_value, list):
            raise StashError("stash.json: 'files' must be a list")

        files = tuple(
            FileRecord.from_dict(item, index=index)
            for index, item in enumerate(files_value)
        )
        return cls(version=version, root=root, label=label, files=files)


def require_string(value: Any, field: str, context: str) -> str:
    if not isinstance(value, str):
        raise StashError(f"{context}: '{field}' must be a string")
    return value


def require_optional_string(value: Any, field: str, context: str) -> str | None:
    if value is None:
        return None
    if not isinstance(value, str):
        raise StashError(f"{context}: '{field}' must be a string or null")
    return value


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

    try:
        with CONFIG_PATH.open("rb") as stream:
            raw_config: dict[str, Any] = tomllib.load(stream)
    except tomllib.TOMLDecodeError as exc:
        raise StashError(f"Invalid TOML in {CONFIG_PATH}: {exc}") from exc
    except UnicodeDecodeError as exc:
        raise StashError(f"{CONFIG_PATH} is not valid UTF-8: {exc}") from exc
    except OSError as exc:
        raise StashError(f"Could not read {CONFIG_PATH}: {exc}") from exc

    if "stash" in raw_config:
        table_value = raw_config["stash"]
        if not isinstance(table_value, dict):
            raise StashError("Config key 'stash' must be a table")
        table: dict[str, Any] = table_value
    else:
        table = raw_config

    ignore_value = table.get("ignore", table.get("ignore_patterns"))
    if not isinstance(ignore_value, list) or not all(
        isinstance(pattern, str) for pattern in ignore_value
    ):
        raise StashError("Config 'ignore' must be a list of glob strings")
    if any(not pattern.strip() for pattern in ignore_value):
        raise StashError("Config 'ignore' must not contain empty patterns")

    batch_size = table.get("batch_size")
    if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0:
        raise StashError("Config 'batch_size' must be a positive integer")

    label = require_optional_string(table.get("label"), "label", str(CONFIG_PATH))

    return Config(
        ignore_patterns=tuple(ignore_value),
        batch_size=batch_size,
        label=label,
    )


def load_stash_data() -> 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:
        text = STASH_PATH.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        raise StashError(f"{STASH_PATH} is not valid UTF-8: {exc}") from exc
    except OSError as exc:
        raise StashError(f"Could not read {STASH_PATH}: {exc}") from exc

    try:
        raw_data: Any = json.loads(text)
    except json.JSONDecodeError as exc:
        raise StashError(f"Invalid JSON in {STASH_PATH}: {exc}") from exc

    return StashData.from_dict(raw_data)


def write_stash_data(data: StashData) -> None:
    text = json.dumps(data.to_dict(), indent=2, ensure_ascii=False) + "\n"
    try:
        STASH_PATH.write_text(text, encoding="utf-8")
    except OSError as exc:
        raise StashError(f"Could not write {STASH_PATH}: {exc}") from exc


def contains_glob(pattern: str) -> bool:
    return any(char in pattern for char in "*?[")


def is_ignored(relative_path: str, patterns: Sequence[str]) -> bool:
    rel = relative_path.replace(os.sep, "/")
    path = PurePosixPath(rel)
    name = path.name
    parts = path.parts

    for raw_pattern in patterns:
        pattern = raw_pattern.strip().replace("\\", "/")
        while pattern.startswith("./"):
            pattern = pattern[2:]

        anchored = pattern.startswith("/")
        if anchored:
            pattern = pattern[1:]
        pattern = pattern.rstrip("/")
        if not pattern:
            continue

        glob = contains_glob(pattern)

        if anchored:
            if fnmatch.fnmatchcase(rel, pattern):
                return True
            if not glob and (rel == pattern or rel.startswith(pattern + "/")):
                return True
            continue

        if fnmatch.fnmatchcase(name, pattern):
            return True
        if fnmatch.fnmatchcase(rel, pattern):
            return True
        if any(fnmatch.fnmatchcase(part, pattern) for part in parts[:-1]):
            return True
        try:
            if path.match(pattern):
                return True
        except ValueError:
            pass
        if not glob and (rel == pattern or rel.startswith(pattern + "/")):
            return True

    return False


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


def iter_candidate_files(root: Path, ignore_patterns: Sequence[str]) -> Iterator[Path]:
    for current_dir, dirnames, filenames in os.walk(
        root,
        topdown=True,
        onerror=walk_error,
        followlinks=False,
    ):
        current_path = Path(current_dir)

        kept_dirs: list[str] = []
        for dirname in dirnames:
            candidate = current_path / dirname
            relative = candidate.relative_to(root).as_posix()
            if not is_ignored(relative, ignore_patterns):
                kept_dirs.append(dirname)
        dirnames[:] = sorted(kept_dirs)

        for filename in sorted(filenames):
            candidate = current_path / filename
            relative = candidate.relative_to(root).as_posix()
            if is_ignored(relative, ignore_patterns):
                continue
            if candidate.is_file():
                yield candidate


def batched(items: Sequence[Path], size: int) -> Iterator[list[Path]]:
    for start in range(0, len(items), size):
        yield list(items[start : start + size])


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""):
            digest.update(chunk)
    return digest.hexdigest()


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


def make_record(path: Path, root: Path) -> FileRecord:
    stat_result = path.stat()
    return FileRecord(
        path=path.relative_to(root).as_posix(),
        size_bytes=stat_result.st_size,
        sha256=sha256_file(path),
        modified_utc=utc_timestamp(stat_result.st_mtime),
    )


def scan(directory: str | Path, config: Config) -> int:
    raw_path = Path(directory).expanduser()
    try:
        root = raw_path.resolve(strict=True)
    except OSError as exc:
        raise StashError(f"Directory not found: {raw_path}") from exc

    if not root.is_dir():
        raise StashError(f"Not a directory: {root}")

    if config.label:
        print(f"Label: {config.label}")
    print(f"Scanning: {root}")

    candidates = list(iter_candidate_files(root, config.ignore_patterns))
    total_files = len(candidates)
    total_batches = (total_files + config.batch_size - 1) // config.batch_size if total_files else 0

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

    records: list[FileRecord] = []
    for batch_number, batch in enumerate(batched(candidates, config.batch_size), start=1):
        for path in batch:
            try:
                records.append(make_record(path, root))
            except OSError as exc:
                raise StashError(f"Could not read {path}: {exc}") from exc
        hashed = min(batch_number * config.batch_size, total_files)
        print(
            f"Batch {batch_number}/{total_batches}: hashed {hashed}/{total_files} file(s)",
            flush=True,
        )

    write_stash_data(
        StashData(
            version=STASH_VERSION,
            root=str(root),
            label=config.label,
            files=tuple(records),
        )
    )
    print(f"Wrote {len(records)} record(s) to {STASH_PATH}")
    return 0


def group_by_extension(files: Sequence[FileRecord]) -> dict[str, list[FileRecord]]:
    groups: dict[str, list[FileRecord]] = {}
    for record in files:
        groups.setdefault(record.extension(), []).append(record)
    return groups


def extension_sort_key(extension: str) -> tuple[bool, str]:
    return (extension == NO_EXTENSION, extension.lower())


def newest_by_extension(groups: dict[str, list[FileRecord]]) -> dict[str, FileRecord]:
    return {
        extension: max(records, key=lambda record: (record.modified_datetime(), record.path))
        for extension, records in groups.items()
    }


def report(_config: Config) -> int:
    data = load_stash_data()
    groups = group_by_extension(data.files)

    if not groups:
        print("No files recorded in stash.json.")
        return 0

    if data.label:
        print(f"Label: {data.label}")
    print(f"Root: {data.root}")
    print()

    header = f"{'Extension':<16} {'Files':>7} {'Total bytes':>15}  Newest file"
    print(header)
    print("-" * len(header))

    newest = newest_by_extension(groups)
    for extension in sorted(groups, key=extension_sort_key):
        records = groups[extension]
        newest_record = newest[extension]
        total_bytes = sum(record.size_bytes for record in records)
        print(
            f"{extension:<16} "
            f"{len(records):>7,} "
            f"{total_bytes:>15,}  "
            f"{newest_record.path} ({newest_record.modified_utc})"
        )

    return 0


def ensure_archive_dir() -> None:
    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


def resolve_stash_root(root_text: str) -> Path:
    root = Path(root_text).expanduser()
    if not root.is_absolute():
        raise StashError(f"Stash root is not an absolute path: {root_text}")
    try:
        resolved = root.resolve(strict=True)
    except OSError as exc:
        raise StashError(f"Scanned directory no longer exists: {root}") from exc
    if not resolved.is_dir():
        raise StashError(f"Stash root is not a directory: {resolved}")
    return resolved


def is_same_file(left: Path, right: Path) -> bool:
    try:
        return left.exists() and left.is_file() and left.samefile(right)
    except OSError:
        return False


def choose_destination(source: Path, relative: Path) -> Path:
    base = relative.name
    if not base:
        raise StashError(f"Recorded file has no filename: {relative.as_posix()}")

    candidate = ARCHIVE_DIR / base
    if not candidate.exists() or is_same_file(candidate, source):
        return candidate

    stem = relative.stem or "file"
    suffix = relative.suffix
    counter = 1
    while True:
        candidate = ARCHIVE_DIR / f"{stem}-{counter}{suffix}"
        if not candidate.exists() or is_same_file(candidate, source):
            return candidate
        counter += 1


def archive(_config: Config) -> int:
    data = load_stash_data()
    groups = group_by_extension(data.files)

    ensure_archive_dir()

    if not groups:
        print("No files recorded in stash.json.")
        return 0

    root = resolve_stash_root(data.root)
    newest = newest_by_extension(groups)

    if data.label:
        print(f"Label: {data.label}")

    copied = 0
    up_to_date = 0

    for extension in sorted(groups, key=extension_sort_key):
        record = newest[extension]
        relative = Path(record.path)

        if relative.is_absolute() or any(part == ".." for part in relative.parts):
            raise StashError(f"Unsafe recorded path: {record.path!r}")

        source = root / relative
        try:
            source_is_file = source.is_file()
        except OSError as exc:
            raise StashError(f"Could not access recorded file {relative.as_posix()}: {exc}") from exc

        if not source_is_file:
            raise StashError(f"Recorded file no longer exists: {source}")

        destination = choose_destination(source, relative)

        if is_same_file(destination, source):
            print(f"{extension}: already up to date ({destination.name})")
            up_to_date += 1
            continue

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

        print(f"{extension}: {relative.as_posix()} -> {destination.name}")
        copied += 1

    summary = f"Archived {copied} file(s) into {ARCHIVE_DIR}"
    if up_to_date:
        summary += f"; {up_to_date} already up to date"
    print(summary)
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="stash",
        description="Scan, report, and archive files according to stash.toml.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")

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

    subparsers.add_parser("report", help="summarize files in stash.json by extension")
    subparsers.add_parser("archive", help="copy the newest file of each extension")

    return parser


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

    try:
        config = load_config()

        if args.command == "scan":
            return scan(args.directory, config)
        if args.command == "report":
            return report(config)
        if args.command == "archive":
            return archive(config)

        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


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

The Small Option

While adding an --ext option, Hy4 flash 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,10 +15,17 @@


-def collect_sizes(root, min_size):
+def collect_sizes(root, min_size, ext=None):
     # TODO: skip symlinks?
+    if ext and not ext.startswith("."):
+        ext = "." + ext
+
     sizes = []
     for dirpath, dirnames, filenames in os.walk(root):
         for i in range(len(filenames)):
-            path = os.path.join(dirpath, filenames[i])
+            filename = filenames[i]
+            if ext and not filename.endswith(ext):
+                continue
+
+            path = os.path.join(dirpath, filename)
             try:
                 size = os.path.getsize(path)
@@ -40,4 +47,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", default=None, help="only count files with this extension, e.g. .log")
     args = parser.parse_args()

@@ -47,5 +55,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.

Python’s standard library itertools doesn’t have a flatten() function, but chain.from_iterable() is the equivalent. Here’s the snippet:

Language: Python
import itertools

list_of_lists = [[1, 2, 3], [4, 5], [6]]
flat = list(itertools.chain.from_iterable(list_of_lists))
print(flat)  # [1, 2, 3, 4, 5, 6]

If you specifically want a function named flatten, use the third-party more_itertools library:

Language: Python
from more_itertools import flatten

list_of_lists = [[1, 2, 3], [4, 5], [6]]
flat = list(flatten(list_of_lists))

Cost and Effort by Task

Task Time Output tokens Thinking tokens Cost
The snake 1 min 32 s 15.8k 13.3k $0.002
The stash tool 2 min 24 s 26.8k 22.2k $0.004
Newest Python 6 s 946 941 $0.000
The small option 16 s 2.6k 2.1k $0.000
The made-up function 5 s 828 654 $0.000
Total 4 min 24 s 47.0k 39.2k $0.007

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 Hy4 flash 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