Chapter 8, Exercise 2: Extended type audit ========================================== Script (extra checks: weights, small print, language; 'unfinished' page added; importance numbers decide which failed check is reported first): """Extended type audit with three extra checks and an 'unfinished' page.""" def channel(v): v = v / 255 return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4 def luminance(h): r, g, b = (int(h[i:i + 2], 16) for i in (1, 3, 5)) return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) def ratio(fg, bg): a, b = sorted((luminance(fg), luminance(bg)), reverse=True) return (a + 0.05) / (b + 0.05) # (name, test, importance: lower number = fix first) CHECKS = [ ("Body size at least 16px", lambda p: p["body_px"] >= 16, 2), ("Line height 1.4 to 1.7", lambda p: 1.4 <= p["line_height"] <= 1.7, 4), ("Measure 45 to 75 characters", lambda p: 45 <= p["measure"] <= 75, 3), ("Body contrast 4.5:1 or more", lambda p: ratio(p["text"], p["bg"]) >= 4.5, 1), ("Two families or fewer", lambda p: len(p["families"]) <= 2, 6), ("Left-aligned body text", lambda p: p["align"] == "left", 5), ("Three font weights or fewer", lambda p: len(p["weights"]) <= 3, 8), ("Small print at least 14px", lambda p: p["small_px"] >= 14, 7), ("Language declared", lambda p: bool(p["lang"]), 9), ] pages = { "before": {"body_px": 12, "line_height": 1.1, "measure": 130, "text": "#aaaaaa", "bg": "#ffffff", "families": ["A", "B", "C", "D"], "align": "justify", "weights": [100, 400, 700, 900], "small_px": 9, "lang": ""}, "after": {"body_px": 18, "line_height": 1.55, "measure": 66, "text": "#333333", "bg": "#ffffff", "families": ["A", "B"], "align": "left", "weights": [400, 700], "small_px": 14, "lang": "en"}, "unfinished": {"body_px": 17, "line_height": 1.5, "measure": 90, "text": "#777777", "bg": "#ffffff", "families": ["A", "B"], "align": "left", "weights": [400, 700], "small_px": 12, "lang": "en"}, } for label, page in pages.items(): failed = [(imp, name) for name, test, imp in CHECKS if not test(page)] print(f"{label:<11} {len(CHECKS) - len(failed)}/{len(CHECKS)} passed") if failed: print(f"{'':<11} fix first: {min(failed)[1]}") Output as printed: before 0/9 passed fix first: Body contrast 4.5:1 or more after 9/9 passed unfinished 6/9 passed fix first: Body contrast 4.5:1 or more Why contrast comes first: it affects every word for every reader, so a failure there outranks everything else.