A confident docstring over a silent bug
Read the code top to bottom. **BAD** is the agent's function, with its claim in the docstring. The **trace** under it follows one call: 25 items, page `-1`, `size=10`. Python reads negative indices from the end, so the slice lands on rows 5–14. You get real data for a page that doesn't exist, and no error. **BETTER** rejects page numbers and sizes below 1 with a `ValueError`, and its docstring states what happens past the end.
Later cost of BAD: wrong rows shown, with no error anywhere.
// Python
# BAD
def page(items, n, size):
"""1-based page n. Handles all edge cases,
including empty and out-of-range pages."""
start = (n - 1) * size
return items[start:start + size]
# Trace: 25 items, page(items, -1, 10)
# start = (-1 - 1) * 10 = -20
# index: 0..4 5..14 15..24
# from end: -25..-21 -20..-11 -10..-1
# ^^^^^^^^
# items[-20:-10]
# page -1 returns real rows 5-14, no error
# BETTER
def page(items, n, size):
"""1-based page n.
Pages past the end return []."""
if n < 1 or size < 1:
raise ValueError("n, size must be >= 1")
start = (n - 1) * size
return items[start:start + size]