We asked MiniMax M4 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:

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.
New Model Drops? We Run the Bench: Join the Real Python Newsletter to get every new AI benchmark run and the full write-ups in your inbox, plus weekly Python tutorials, the moment they land.
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 | 5767 drawing commands, 376 lines of code |
| How modern its Python is | Python 3.11 (2022) | pinned by path_walk. Newest feature used: Python 3.12 |
| Modern idioms | 10 of 15 | of the checkpoints that applied to its code |
| Latest Python version reported | 3.14.4 | 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 | 71.7k thinking tokens over all five tasks |
| Cost | $0.25 | for all 5 tasks, as billed by the API |
| Response time | 14 min 27 s | 81.8k output tokens |
The run: minimax/minimax-m4 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.
turtle.py
import math
import turtle
# ------------------------------------------------------------------
# Screen and drawing turtle
# ------------------------------------------------------------------
screen = turtle.Screen()
screen.setup(900, 700)
screen.title("A Python Reading a Book")
screen.bgcolor("#f6f0e1")
screen.tracer(0) # Draw everything first, then display it in one go
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()
BODY = "#43a047" # Snake green
BODY_EDGE = "#1b5e20" # Dark outline
SPOT = "#2e7d32" # Darker patches
HEAD = "#4caf50" # Slightly lighter head
# ------------------------------------------------------------------
# Helper functions
# ------------------------------------------------------------------
def fill_polygon(points, fill, outline=None, width=1):
"""Draw a filled polygon from a list of (x, y) points."""
pen.penup()
pen.goto(*points[0])
pen.fillcolor(fill)
pen.pencolor(outline or fill)
pen.pensize(width)
pen.pendown()
pen.begin_fill()
for p in points[1:]:
pen.goto(*p)
pen.goto(*points[0])
pen.end_fill()
pen.penup()
def draw_path(points, color, width=1):
"""Draw an open polyline."""
pen.penup()
pen.goto(*points[0])
pen.pencolor(color)
pen.pensize(width)
pen.pendown()
for p in points[1:]:
pen.goto(*p)
pen.penup()
def draw_circle(x, y, r, fill=None, outline=None, width=1):
"""Draw a circle centered on (x, y)."""
pen.penup()
pen.goto(x, y - r)
pen.setheading(0)
pen.pencolor(outline or fill or "black")
pen.pensize(width)
if fill:
pen.fillcolor(fill)
pen.begin_fill()
pen.pendown()
pen.circle(r)
if fill:
pen.end_fill()
pen.penup()
def ellipse_points(cx, cy, rx, ry, n=90):
"""Points around an ellipse."""
return [
(cx + rx * math.cos(2 * math.pi * i / n),
cy + ry * math.sin(2 * math.pi * i / n))
for i in range(n)
]
def quad_curve(p0, p1, p2, n=16):
"""Points on a quadratic Bezier curve; p1 is the control point."""
pts = []
for i in range(n + 1):
t = i / n
pts.append((
(1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0],
(1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]
))
return pts
def catmull_rom(points, samples=25):
"""Create a smooth curve passing through the given points."""
curve = []
for i in range(len(points) - 1):
p0 = points[max(i - 1, 0)]
p1 = points[i]
p2 = points[i + 1]
p3 = points[min(i + 2, len(points) - 1)]
for s in range(samples):
t = s / 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
)
curve.append((x, y))
curve.append(points[-1])
return curve
def resample(points, spacing):
"""Return points spaced evenly along a polyline."""
lengths = [0.0]
for (x0, y0), (x1, y1) in zip(points, points[1:]):
lengths.append(lengths[-1] + math.hypot(x1 - x0, y1 - y0))
count = int(lengths[-1] / spacing)
result = []
j = 0
for k in range(count + 1):
target = k * spacing
while j < len(points) - 2 and lengths[j + 1] < target:
j += 1
segment = lengths[j + 1] - lengths[j]
t = 0.0 if segment == 0 else (target - lengths[j]) / segment
result.append((
points[j][0] + (points[j + 1][0] - points[j][0]) * t,
points[j][1] + (points[j + 1][1] - points[j][1]) * t
))
return result
def mirror(points):
"""Mirror points across the y-axis."""
return [(-x, y) for x, y in points]
# ------------------------------------------------------------------
# Rug and shadow
# ------------------------------------------------------------------
fill_polygon(ellipse_points(0, -235, 410, 80), "#cfe8d5", "#8fbf9f", 3)
rug_border = ellipse_points(0, -235, 385, 62)
draw_path(rug_border + rug_border[:1], "#a9d6b8", 2)
fill_polygon(ellipse_points(0, -212, 250, 28), "#b5d8c0")
# ------------------------------------------------------------------
# Snake body
# ------------------------------------------------------------------
# Center line of the snake, from tail tip to neck
spine = [
(-325, 40), (-365, -20), (-350, -90), (-280, -135), # Tail on the left
(-150, -145), (0, -140), (150, -135), # Hidden by the book
(270, -100), (325, -10), (310, 100), # Rising on the right
(240, 180), (140, 220), (60, 210), # Arching over the book
(15, 170), (0, 130), (0, 105) # Neck
]
path = resample(catmull_rom(spine), 2.0)
arc_length = [i * 2.0 for i in range(len(path))]
total_length = arc_length[-1]
BODY_RADIUS = 28.0
def body_radius(distance):
"""Tail tapers to a point; the neck is slightly thinner."""
t = min(1.0, distance / 220.0)
radius = 3 + (BODY_RADIUS - 3) * t * t * (3 - 2 * t)
n = min(1.0, (total_length - distance) / 80.0)
return radius - 6 * (1 - n * n * (3 - 2 * n))
radii = [body_radius(d) for d in arc_length]
# First pass draws the dark outline; second pass fills the body.
for (x, y), r in zip(path, radii):
pen.goto(x, y)
pen.dot(2 * (r + 3 * min(1.0, r / 12.0)), BODY_EDGE)
for (x, y), r in zip(path, radii):
pen.goto(x, y)
pen.dot(2 * r, BODY)
# Alternating dark patches along the body
distance = 40.0
side = 1
while distance < total_length - 30:
i = int(distance / 2.0)
x, y = path[i]
x0, y0 = path[i - 1]
x1, y1 = path[i + 1]
tx, ty = x1 - x0, y1 - y0
length = math.hypot(tx, ty)
nx, ny = -ty / length, tx / length
r = radii[i]
draw_circle(
x + side * 0.42 * r * nx,
y + side * 0.42 * r * ny,
0.27 * r,
fill=SPOT
)
side = -side
distance += 36.0
# ------------------------------------------------------------------
# Open book
# ------------------------------------------------------------------
cover = [
(-215, 0), (0, -22), (215, 0),
(225, -198), (0, -214), (-225, -198)
]
fill_polygon(cover, "#7b2d26", "#3e1512", 3)
# The left half; the right half is its mirror image.
page_left = [
(0, -34), (-35, -24), (-100, -18), (-165, -20), (-202, -26),
(-210, -184), (-165, -180), (-100, -180), (-35, -188), (0, -204)
]
block_left = [
(0, -34), (-35, -24), (-100, -18), (-165, -20), (-202, -26),
(-209, -28), (-217, -190), (-165, -190), (-100, -190),
(-35, -198), (0, -212)
]
page_edges_left = [
(-205, -27), (-213, -187), (-165, -185),
(-100, -185), (-35, -193), (0, -208)
]
gutter_shade_left = [(0, -34), (-16, -28), (-17, -193), (0, -204)]
for shape, fill, outline in [
(block_left, "#e6dcc3", "#b9ad8f"),
(page_left, "#fff8e7", "#b9ad8f"),
(gutter_shade_left, "#efe5cc", None),
]:
fill_polygon(shape, fill, outline)
fill_polygon(mirror(shape), fill, outline)
draw_path(page_edges_left, "#cfc5ab")
draw_path(mirror(page_edges_left), "#cfc5ab")
draw_path([(0, -34), (0, -212)], "#a89c7e", 2)
def page_line(side, x_outer, x_inner, y_outer, y_inner, color, width=2):
"""Draw a line of text that follows the curve of a page."""
p0 = (side * x_outer, y_outer)
p2 = (side * x_inner, y_inner)
p1 = ((p0[0] + p2[0]) / 2, (p0[1] + p2[1]) / 2 + 14)
draw_path(quad_curve(p0, p1, p2), color, width)
# Left page: heading and text
page_line(-1, 150, 60, -50, -57, "#6b5b4a", 4)
for i in range(6):
inner_x = 28 if i < 5 else 95
page_line(
-1, 185, inner_x,
-72 - 18 * i, -80 - 18 * i,
"#9a8f7c"
)
# Right page: a small picture of a snake, followed by text
fill_polygon(
[(60, -50), (172, -48), (174, -108), (62, -112)],
"#e8f5e9", "#81c784"
)
tiny_snake = catmull_rom([
(78, -92), (92, -68), (108, -88),
(124, -66), (140, -90), (156, -74)
], 12)
draw_path(tiny_snake, "#2e7d32", 5)
draw_circle(156, -74, 5, fill="#2e7d32")
for i in range(3):
inner_x = 28 if i < 2 else 110
page_line(
1, 185, inner_x,
-132 - 18 * i, -140 - 18 * i,
"#9a8f7c"
)
# Bookmark ribbon
fill_polygon(
[(5, -206), (17, -206), (17, -262), (11, -252), (5, -262)],
"#f2b632", "#b07d12"
)
# ------------------------------------------------------------------
# Snake's head
# ------------------------------------------------------------------
def draw_head(cx, cy):
# Forked tongue, drawn first so the snout overlaps its root
draw_path([(cx, cy - 52), (cx, cy - 70)], "#d32f2f", 4)
draw_path(
[(cx - 9, cy - 82), (cx, cy - 70), (cx + 9, cy - 82)],
"#d32f2f", 4
)
# Egg-shaped head: wide at the back, narrower at the snout
head_points = []
for i in range(72):
angle = 2 * math.pi * i / 72
head_points.append((
cx + 44 * math.sin(angle) * (1 + 0.22 * math.cos(angle)),
cy + 52 * math.cos(angle)
))
fill_polygon(head_points, HEAD, BODY_EDGE, 3)
# Nostrils
draw_circle(cx - 6, cy - 34, 1.8, fill=BODY_EDGE)
draw_circle(cx + 6, cy - 34, 1.8, fill=BODY_EDGE)
# Half-closed eyes looking down at the pages
for ex in (cx - 20, cx + 20):
ey = cy + 10
draw_circle(ex, ey, 12, fill="white", outline=BODY_EDGE, width=2)
draw_circle(ex, ey - 4.5, 6, fill="#1b1b1b")
draw_circle(ex - 2, ey - 2.5, 1.7, fill="white")
eyelid = [
(ex + 12.5 * math.cos(math.radians(a)),
ey + 12.5 * math.sin(math.radians(a)))
for a in range(15, 166, 10)
]
fill_polygon(eyelid, HEAD, BODY_EDGE, 2)
# Reading glasses
for ex in (cx - 20, cx + 20):
draw_circle(ex, cy + 10, 16, outline="#3e2723", width=3)
draw_path(
quad_curve((cx - 4, cy + 13), (cx, cy + 19), (cx + 4, cy + 13), 8),
"#3e2723", 3
)
draw_path([(cx - 36, cy + 13), (cx - 39, cy + 32)], "#3e2723", 3)
draw_path([(cx + 36, cy + 13), (cx + 39, cy + 32)], "#3e2723", 3)
draw_head(0, 70)
# ------------------------------------------------------------------
# Finish
# ------------------------------------------------------------------
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 10 of the 15 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 itertools.batched(), introduced in Python 3.12.
| 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 | ✅ modern | 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 | ✅ modern | 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 | ❌ stale | except A, B: |
except (A, B): |
no_future_annotations |
3.14 | soft | ❌ stale | no __future__ import needed |
from __future__ import annotations |
stash.py
#!/usr/bin/env python3
"""stash: scan, summarize, and archive files by extension.
Requires Python 3.13 or newer.
Configuration is read from ``stash.toml`` next to this script::
ignore = ["*.tmp", "**/__pycache__/**"]
batch_size = 100
# label = "optional label"
Patterns without a slash match a file or directory name at any depth.
Patterns containing a slash match paths relative to the scan root; a leading
slash anchors the pattern to that root. A trailing slash makes a pattern
directory-only.
``stash.json`` and ``archive/`` are stored next to this script.
"""
from __future__ import annotations
import argparse
from collections.abc import Iterable, Sequence
from contextlib import suppress
from dataclasses import dataclass
from datetime import UTC, datetime
import hashlib
from itertools import batched
import json
import os
from pathlib import Path, PurePath, PurePosixPath
import re
import shutil
import sys
import tempfile
import time
import tomllib
from typing import Final, Never, cast
SCRIPT_DIR: Final = Path(__file__).resolve().parent
CONFIG_PATH: Final = SCRIPT_DIR / "stash.toml"
STASH_PATH: Final = SCRIPT_DIR / "stash.json"
ARCHIVE_DIR: Final = SCRIPT_DIR / "archive"
STASH_FORMAT: Final = 1
NO_EXTENSION: Final = "<none>"
GLOB_CASE_SENSITIVE: Final = os.name != "nt"
EPOCH: Final = datetime(1970, 1, 1, tzinfo=UTC)
_TIMESTAMP_PATTERN: Final = re.compile(
r"(?P<date>\d{4}-\d{2}-\d{2})T"
r"(?P<time>\d{2}:\d{2}:\d{2})"
r"(?:\.(?P<fraction>\d{1,9}))?"
r"(?P<offset>Z|[+-]\d{2}:\d{2})"
)
_CONFIG_KEYS: Final = frozenset({"ignore", "batch_size", "label"})
class StashError(Exception):
"""An expected, user-facing stash failure."""
@dataclass(frozen=True, slots=True, order=True)
class UtcTimestamp:
"""A UTC Unix timestamp with nanosecond precision."""
nanoseconds: int
@classmethod
def now(cls) -> UtcTimestamp:
return cls(time.time_ns())
@classmethod
def from_isoformat(cls, value: str) -> UtcTimestamp:
match = _TIMESTAMP_PATTERN.fullmatch(value)
if match is None:
raise ValueError("expected an RFC 3339 timestamp with a UTC offset")
fraction = match.group("fraction") or ""
fraction_nanoseconds = int(fraction.ljust(9, "0")) if fraction else 0
try:
instant = datetime.fromisoformat(
f"{match.group('date')}T{match.group('time')}{match.group('offset')}"
)
except ValueError as exc:
raise ValueError("invalid timestamp") from exc
delta = instant - EPOCH
whole_seconds = delta.days * 86_400 + delta.seconds
return cls(whole_seconds * 1_000_000_000 + fraction_nanoseconds)
def to_isoformat(self) -> str:
seconds, nanoseconds = divmod(self.nanoseconds, 1_000_000_000)
instant = datetime.fromtimestamp(seconds, UTC)
prefix = instant.isoformat(timespec="seconds").removesuffix("+00:00")
return f"{prefix}.{nanoseconds:09d}Z"
def __str__(self) -> str:
return self.to_isoformat()
@dataclass(frozen=True, slots=True)
class Config:
ignore_patterns: tuple[str, ...]
batch_size: int
label: str | None
@dataclass(frozen=True, slots=True)
class GlobPattern:
text: str
directory_only: bool
match_name: bool
@classmethod
def parse(cls, pattern: str) -> GlobPattern:
if not pattern:
raise StashError("ignore patterns must not be empty")
if "\0" in pattern:
raise StashError(f"invalid ignore pattern {pattern!r}: NUL is not allowed")
if os.name == "nt":
pattern = pattern.replace("\\", "/")
directory_only = pattern.endswith("/")
text = pattern.rstrip("/")
anchored = text.startswith("/")
text = text.lstrip("/")
if not text:
raise StashError(f"invalid ignore pattern {pattern!r}")
try:
PurePosixPath("stash").full_match(
text,
case_sensitive=GLOB_CASE_SENSITIVE,
)
except ValueError as exc:
raise StashError(f"invalid ignore pattern {pattern!r}: {exc}") from exc
return cls(
text=text,
directory_only=directory_only,
match_name=not anchored and "/" not in text,
)
def matches(self, path: PurePosixPath, *, is_directory: bool) -> bool:
if self.directory_only and not is_directory:
return False
target = PurePosixPath(path.name) if self.match_name else path
return target.full_match(
self.text,
case_sensitive=GLOB_CASE_SENSITIVE,
)
@dataclass(frozen=True, slots=True)
class IgnoreMatcher:
patterns: tuple[GlobPattern, ...]
@classmethod
def from_strings(cls, patterns: Iterable[str]) -> IgnoreMatcher:
return cls(tuple(GlobPattern.parse(pattern) for pattern in patterns))
def matches(self, path: PurePosixPath, *, is_directory: bool) -> bool:
return any(
pattern.matches(path, is_directory=is_directory)
for pattern in self.patterns
)
@dataclass(frozen=True, slots=True)
class FileCandidate:
path: Path
relative_path: PurePosixPath
@dataclass(frozen=True, slots=True)
class FileRecord:
path: PurePosixPath
size: int
sha256: str
modified: UtcTimestamp
@dataclass(frozen=True, slots=True)
class Manifest:
root: Path
scanned_at: UtcTimestamp
label: str | None
files: tuple[FileRecord, ...]
@dataclass(frozen=True, slots=True)
class ExtensionSummary:
extension: str
file_count: int
total_size: int
newest: FileRecord
@dataclass(frozen=True, slots=True)
class ArchiveItem:
summary: ExtensionSummary
source: Path
destination: Path
def load_config(path: Path) -> Config:
try:
with path.open("rb") as handle:
raw: dict[str, object] = tomllib.load(handle)
except FileNotFoundError as exc:
raise StashError(
f"configuration file not found: {path} "
"(expected stash.toml next to the script)"
) from exc
except tomllib.TOMLDecodeError as exc:
raise StashError(f"invalid TOML in {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"cannot read configuration file {path}: {exc}") from exc
unknown_keys = sorted(raw.keys() - _CONFIG_KEYS)
if unknown_keys:
raise StashError(
f"unsupported key(s) in {path}: {', '.join(unknown_keys)}"
)
for required_key in ("ignore", "batch_size"):
if required_key not in raw:
raise StashError(f"missing required key {required_key!r} in {path}")
ignore_value = raw["ignore"]
if not isinstance(ignore_value, list):
raise StashError(f"{path}: 'ignore' must be an array of strings")
ignore_items = cast(list[object], ignore_value)
ignore_patterns: list[str] = []
for index, item in enumerate(ignore_items):
if not isinstance(item, str):
raise StashError(
f"{path}: ignore[{index}] must be a string, not {type(item).__name__}"
)
ignore_patterns.append(item)
batch_size = raw["batch_size"]
if isinstance(batch_size, bool) or not isinstance(batch_size, int):
raise StashError(f"{path}: 'batch_size' must be a positive integer")
if batch_size < 1:
raise StashError(f"{path}: 'batch_size' must be at least 1")
label_value = raw.get("label")
if label_value is not None and not isinstance(label_value, str):
raise StashError(f"{path}: 'label' must be a string when provided")
IgnoreMatcher.from_strings(ignore_patterns)
return Config(
ignore_patterns=tuple(ignore_patterns),
batch_size=batch_size,
label=cast(str | None, label_value),
)
def _expect_mapping(value: object, context: str) -> dict[str, object]:
if not isinstance(value, dict):
raise StashError(f"{context} must be a JSON object")
return cast(dict[str, object], value)
def _expect_list(value: object, context: str) -> list[object]:
if not isinstance(value, list):
raise StashError(f"{context} must be a JSON array")
return cast(list[object], value)
def _expect_string(value: object, context: str) -> str:
if not isinstance(value, str):
raise StashError(f"{context} must be a string")
return value
def _expect_integer(value: object, context: str) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise StashError(f"{context} must be an integer")
return value
def _parse_relative_path(value: object, context: str) -> PurePosixPath:
text = _expect_string(value, context)
if "\0" in text:
raise StashError(f"{context} contains a NUL character")
if text.endswith("/"):
raise StashError(f"{context} must identify a file, not a directory")
path = PurePosixPath(text)
native_path = PurePath(text)
if (
not path.parts
or path.is_absolute()
or ".." in path.parts
or native_path.is_absolute()
or native_path.drive
or ".." in native_path.parts
):
raise StashError(f"{context} must be a safe relative file path")
return path
def _record_from_json(value: object, context: str) -> FileRecord:
mapping = _expect_mapping(value, context)
for required_key in ("path", "size", "sha256", "modified"):
if required_key not in mapping:
raise StashError(f"{context} is missing {required_key!r}")
path = _parse_relative_path(mapping["path"], f"{context}.path")
size = _expect_integer(mapping["size"], f"{context}.size")
if size < 0:
raise StashError(f"{context}.size must not be negative")
digest = _expect_string(mapping["sha256"], f"{context}.sha256")
if len(digest) != 64 or any(
character not in "0123456789abcdef" for character in digest
):
raise StashError(f"{context}.sha256 must be a lowercase SHA-256 digest")
modified_text = _expect_string(mapping["modified"], f"{context}.modified")
try:
modified = UtcTimestamp.from_isoformat(modified_text)
except ValueError as exc:
raise StashError(f"{context}.modified is invalid: {exc}") from exc
return FileRecord(path=path, size=size, sha256=digest, modified=modified)
def load_manifest(path: Path) -> Manifest:
try:
with path.open("r", encoding="utf-8") as handle:
raw: object = json.load(handle)
except FileNotFoundError as exc:
raise StashError(
f"stash file not found: {path}; run 'stash scan DIRECTORY' first"
) from exc
except json.JSONDecodeError as exc:
raise StashError(f"invalid JSON in {path}: {exc}") from exc
except UnicodeDecodeError as exc:
raise StashError(f"stash file is not valid UTF-8: {path}") from exc
except OSError as exc:
raise StashError(f"cannot read stash file {path}: {exc}") from exc
mapping = _expect_mapping(raw, str(path))
version = _expect_integer(mapping.get("version"), f"{path}.version")
if version != STASH_FORMAT:
raise StashError(
f"unsupported stash format in {path}: expected version {STASH_FORMAT}, "
f"found {version}"
)
root_text = _expect_string(mapping.get("root"), f"{path}.root")
if "\0" in root_text:
raise StashError(f"{path}.root contains a NUL character")
root = Path(root_text)
if not root.is_absolute():
raise StashError(f"{path}.root must be an absolute path")
scanned_text = _expect_string(mapping.get("scanned_at"), f"{path}.scanned_at")
try:
scanned_at = UtcTimestamp.from_isoformat(scanned_text)
except ValueError as exc:
raise StashError(f"{path}.scanned_at is invalid: {exc}") from exc
label_value = mapping.get("label")
label = (
None
if label_value is None
else _expect_string(label_value, f"{path}.label")
)
file_values = _expect_list(mapping.get("files"), f"{path}.files")
records: list[FileRecord] = []
seen_paths: set[str] = set()
for index, value in enumerate(file_values):
record = _record_from_json(value, f"{path}.files[{index}]")
path_text = record.path.as_posix()
if path_text in seen_paths:
raise StashError(f"{path}.files contains duplicate path {path_text!r}")
seen_paths.add(path_text)
records.append(record)
return Manifest(
root=root,
scanned_at=scanned_at,
label=label,
files=tuple(records),
)
def _remove_temp_file(path: Path | None) -> None:
if path is not None:
with suppress(OSError):
path.unlink(missing_ok=True)
def write_manifest(path: Path, manifest: Manifest) -> None:
files: list[dict[str, object]] = [
{
"path": record.path.as_posix(),
"size": record.size,
"sha256": record.sha256,
"modified": str(record.modified),
}
for record in manifest.files
]
payload: dict[str, object] = {
"version": STASH_FORMAT,
"label": manifest.label,
"root": str(manifest.root),
"scanned_at": str(manifest.scanned_at),
"files": files,
}
temp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=".stash-json-",
suffix=".tmp",
delete=False,
) as handle:
temp_path = Path(handle.name)
json.dump(payload, handle, indent=2, allow_nan=False)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
except OSError as exc:
_remove_temp_file(temp_path)
raise StashError(f"cannot write stash file {path}: {exc}") from exc
except BaseException:
_remove_temp_file(temp_path)
raise
def _raise_walk_error(error: OSError) -> Never:
raise error
def discover_files(root: Path, matcher: IgnoreMatcher) -> list[FileCandidate]:
def relative_path(path: Path) -> PurePosixPath:
return PurePosixPath(path.relative_to(root).as_posix())
candidates: list[FileCandidate] = []
for current, directory_names, file_names in os.walk(
root,
topdown=True,
onerror=_raise_walk_error,
followlinks=False,
):
current_path = Path(current)
kept_directories: list[str] = []
for name in sorted(directory_names):
directory = current_path / name
if not matcher.matches(
relative_path(directory),
is_directory=True,
):
kept_directories.append(name)
directory_names[:] = kept_directories
for name in sorted(file_names):
path = current_path / name
relative = relative_path(path)
if matcher.matches(relative, is_directory=False):
continue
if not path.is_file():
continue
candidates.append(FileCandidate(path=path, relative_path=relative))
candidates.sort(key=lambda candidate: candidate.relative_path.as_posix())
return candidates
def hash_file(candidate: FileCandidate) -> FileRecord:
try:
with candidate.path.open("rb") as handle:
before = os.fstat(handle.fileno())
digest = hashlib.file_digest(handle, "sha256").hexdigest()
after = os.fstat(handle.fileno())
except OSError as exc:
raise StashError(f"cannot hash {candidate.path}: {exc}") from exc
if (before.st_size, before.st_mtime_ns) != (
after.st_size,
after.st_mtime_ns,
):
raise StashError(
f"file changed while it was being hashed: {candidate.path}; "
"run the scan again"
)
modified = UtcTimestamp(after.st_mtime_ns)
try:
modified.to_isoformat()
except (OverflowError, OSError, ValueError) as exc:
raise StashError(
f"cannot represent the modification time of {candidate.path}: {exc}"
) from exc
return FileRecord(
path=candidate.relative_path,
size=after.st_size,
sha256=digest,
modified=modified,
)
def _file_word(count: int) -> str:
return "file" if count == 1 else "files"
def scan(directory: Path, config: Config) -> None:
try:
root = directory.resolve(strict=True)
except FileNotFoundError as exc:
raise StashError(f"scan directory not found: {directory}") from exc
except (OSError, RuntimeError, ValueError) as exc:
raise StashError(f"cannot access scan directory {directory}: {exc}") from exc
if not root.is_dir():
raise StashError(f"scan path is not a directory: {directory}")
matcher = IgnoreMatcher.from_strings(config.ignore_patterns)
try:
candidates = discover_files(root, matcher)
except OSError as exc:
raise StashError(f"cannot scan {root}: {exc}") from exc
records: list[FileRecord] = []
total = len(candidates)
processed = 0
label_prefix = f"[{config.label}] " if config.label else ""
if not candidates:
print(f"{label_prefix}no files to hash", flush=True)
for batch_number, batch in enumerate(
batched(candidates, config.batch_size),
start=1,
):
for candidate in batch:
records.append(hash_file(candidate))
processed += len(batch)
print(
f"{label_prefix}hashed batch {batch_number}: "
f"{len(batch)} {_file_word(len(batch))} "
f"({processed}/{total})",
flush=True,
)
manifest = Manifest(
root=root,
scanned_at=UtcTimestamp.now(),
label=config.label,
files=tuple(records),
)
write_manifest(STASH_PATH, manifest)
print(
f"wrote {len(records)} {_file_word(len(records))} to {STASH_PATH}",
flush=True,
)
def _newest_key(record: FileRecord) -> tuple[UtcTimestamp, str]:
return record.modified, record.path.as_posix()
def summarize_extensions(files: Iterable[FileRecord]) -> tuple[ExtensionSummary, ...]:
summaries: dict[str, ExtensionSummary] = {}
for record in files:
extension = record.path.suffix.lower() or NO_EXTENSION
current = summaries.get(extension)
if current is None:
summaries[extension] = ExtensionSummary(
extension=extension,
file_count=1,
total_size=record.size,
newest=record,
)
continue
newest = (
record
if _newest_key(record) > _newest_key(current.newest)
else current.newest
)
summaries[extension] = ExtensionSummary(
extension=extension,
file_count=current.file_count + 1,
total_size=current.total_size + record.size,
newest=newest,
)
return tuple(
sorted(summaries.values(), key=lambda summary: summary.extension.casefold())
)
def _print_table(
headers: Sequence[str],
rows: Sequence[Sequence[str]],
right_aligned: frozenset[int],
) -> None:
all_rows: list[Sequence[str]] = [headers, *rows]
widths = [
max(len(row[index]) for row in all_rows)
for index in range(len(headers))
]
def format_cell(index: int, text: str) -> str:
if index in right_aligned:
return text.rjust(widths[index])
return text.ljust(widths[index])
print(
" ".join(
format_cell(index, text) for index, text in enumerate(headers)
).rstrip()
)
print(" ".join("-" * width for width in widths).rstrip())
for row in rows:
print(
" ".join(
format_cell(index, text) for index, text in enumerate(row)
).rstrip()
)
def report() -> None:
manifest = load_manifest(STASH_PATH)
summaries = summarize_extensions(manifest.files)
if manifest.label is not None:
print(f"Label: {manifest.label}")
print(f"Root: {manifest.root}")
print(f"Scanned: {manifest.scanned_at}")
if not summaries:
print("No files recorded.")
return
rows: list[tuple[str, ...]] = [
(
summary.extension,
str(summary.file_count),
str(summary.total_size),
summary.newest.path.as_posix(),
str(summary.newest.modified),
)
for summary in summaries
]
_print_table(
headers=("Extension", "Files", "Total bytes", "Newest file", "Modified (UTC)"),
rows=rows,
right_aligned=frozenset({1, 2}),
)
def _copy_atomically(source: Path, destination: Path) -> None:
temp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
dir=destination.parent,
prefix=".stash-copy-",
suffix=".tmp",
delete=False,
) as handle:
temp_path = Path(handle.name)
shutil.copy2(source, temp_path)
os.replace(temp_path, destination)
except OSError as exc:
_remove_temp_file(temp_path)
raise StashError(f"cannot copy {source} to {destination}: {exc}") from exc
except BaseException:
_remove_temp_file(temp_path)
raise
def archive() -> None:
manifest = load_manifest(STASH_PATH)
if not manifest.root.is_dir():
raise StashError(
f"scan root from {STASH_PATH} is not an available directory: "
f"{manifest.root}"
)
plan: list[ArchiveItem] = []
for summary in summarize_extensions(manifest.files):
source = manifest.root.joinpath(*summary.newest.path.parts)
if not source.is_file():
raise StashError(
f"file recorded in {STASH_PATH} is no longer available: "
f"{summary.newest.path} (expected at {source})"
)
plan.append(
ArchiveItem(
summary=summary,
source=source,
destination=ARCHIVE_DIR / summary.newest.path.name,
)
)
try:
ARCHIVE_DIR.mkdir(exist_ok=True)
except OSError as exc:
raise StashError(f"cannot create archive directory {ARCHIVE_DIR}: {exc}") from exc
for item in plan:
_copy_atomically(item.source, item.destination)
print(
f"{item.summary.extension}: "
f"{item.summary.newest.path} -> {item.destination}",
flush=True,
)
print(
f"archived {len(plan)} {_file_word(len(plan))} in {ARCHIVE_DIR}",
flush=True,
)
_CONFIG_HELP: Final = """\
Configuration is read from stash.toml next to this script:
ignore = ["*.tmp", "**/__pycache__/**"]
batch_size = 100
# label = "optional label"
stash.json and archive/ are stored next to this script.
"""
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="stash",
description="Scan files, report statistics by extension, and archive newest files.",
epilog=_CONFIG_HELP,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
subparsers = parser.add_subparsers(
dest="command",
metavar="COMMAND",
required=True,
)
scan_parser = subparsers.add_parser(
"scan",
help="hash files recursively and write stash.json",
description="Hash files recursively and write stash.json.",
)
scan_parser.add_argument(
"directory",
metavar="DIRECTORY",
type=Path,
help="directory to scan recursively",
)
subparsers.add_parser(
"report",
help="print file statistics grouped by extension",
description="Print file statistics grouped by extension.",
)
subparsers.add_parser(
"archive",
help="copy the newest file of each extension into archive/",
description="Copy the newest file of each extension into archive/.",
)
return parser
def main(argv: Sequence[str] | None = None) -> int:
parser = build_parser()
arguments = parser.parse_args(argv)
try:
config = load_config(CONFIG_PATH)
match arguments.command:
case "scan":
scan(cast(Path, arguments.directory), config)
case "report":
report()
case "archive":
archive()
case _:
raise StashError(f"unknown command: {arguments.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
except KeyboardInterrupt:
print("stash: 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.14.4
The Small Option
While adding an --ext option, MiniMax M4 left all 10 unrelated spots alone. You can inspect the diff below to see what it changed.
--- original.py
+++ updated.py
@@ -15,10 +15,14 @@
-def collect_sizes(root, min_size):
+def collect_sizes(root, min_size, ext=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])
+ filename = filenames[i]
+ if ext is not None and os.path.splitext(filename)[1] != ext:
+ continue
+
+ path = os.path.join(dirpath, filename)
try:
size = os.path.getsize(path)
@@ -40,4 +44,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 +52,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 has no flatten(); use chain.from_iterable():
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 | 4 min 58 s | 33.8k | 30.1k | $0.10 |
| The stash tool | 9 min 1 s | 45.5k | 39.6k | $0.14 |
| Newest Python | 10 s | 894 | 889 | $0.003 |
| The small option | 16 s | 1.5k | 1.0k | $0.005 |
| The made-up function | 2 s | 109 | 71 | $0.000 |
| Total | 14 min 27 s | 81.8k | 71.7k | $0.25 |
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 MiniMax M4 compares with every other model we’ve run on the overview page.
New Model Drops? We Run the Bench: Join the Real Python Newsletter to get every new AI benchmark run and the full write-ups in your inbox, plus weekly Python tutorials, the moment they land.
Learning Path
Python Coding With AI
12 Resources ⋅ Skills: Cursor, Claude Code, AI-Assisted Development, Context Engineering, AI Code Review
