Format file sizes for the attachments list

Python · Python · intermediate · greenfield

Adds the `format_size` helper used by the attachments list. Walks the binary units dividing by 1024, keeps bytes as integers, and rounds larger sizes to one decimal. Handles the boundary where rounding alone would display `1024.0 KB` by rolling over to the next unit.

Requirements

Files touched

--- app/files/format_size.py
+UNITS = ["B", "KB", "MB", "GB", "TB"]
+
+
+def format_size(num_bytes):
+    """Human-readable binary size: bytes as an integer, larger units to one decimal."""
+    if isinstance(num_bytes, bool) or not isinstance(num_bytes, int):
+        raise TypeError("num_bytes must be an int")
+    if num_bytes < 0:
+        raise ValueError("num_bytes must be non-negative")
+    if num_bytes < 1024:
+        return f"{num_bytes} B"
+    size = float(num_bytes)
+    unit = 0
+    while size >= 1024 and unit < len(UNITS) - 1:
+        size /= 1024.0
+        unit += 1
+    # Rounding to one decimal can land exactly on 1024.0 (e.g. 1048571 bytes
+    # is 1023.995 KB); roll over so "1024.0 KB" never renders.
+    if round(size, 1) >= 1024 and unit < len(UNITS) - 1:
+        size /= 1024.0
+        unit += 1
+    return f"{size:.1f} {UNITS[unit]}"
+

Review this PR

Python practice