Checkpoint: Stdlib Power Tools

Published by Brayan K

A checkpoint is a chance to consolidate: here you'll review eight standard-library modules and combine several of them in one realistic build challenge before moving on.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Build one report with explicit data and presentation contracts

This checkpoint turns mixed incoming records into a small text report. Each accepted record needs a nonempty name and an integer score from 0 to 100. The legacy points field is still accepted with a warning, but a record containing both names for the score is rejected. Invalid records remain visible in a separate rejection list.

The tools serve distinct jobs: validation decides whether the data is meaningful, operator supplies a field selector, statistics calculates the mean, textwrap formats the summary, warnings reports migration needs and inspect checks the renderer’s call shape. None of them replaces the others.

import warnings
from inspect import signature
from operator import itemgetter
from statistics import fmean
from textwrap import fill

class LegacyPointsWarning(DeprecationWarning):
    pass

def normalize(record):
    name = record.get("name")
    if not isinstance(name, str) or not name.strip():
        raise ValueError("name must be nonempty text")
    if "score" in record and "points" in record:
        raise ValueError("score and points conflict")
    if "score" in record:
        score = record["score"]
    elif "points" in record:
        warnings.warn("points is deprecated; use score",
                      LegacyPointsWarning, stacklevel=2)
        score = record["points"]
    else:
        raise ValueError("score is required")
    if type(score) is not int or not 0 <= score <= 100:
        raise ValueError("score must be an integer from 0 to 100")
    return {"name": name.strip(), "score": score}

def render(records, *, width=40):
    if not records:
        raise ValueError("no accepted records")
    if type(width) is not int or width < 12:
        raise ValueError("width must be an integer of at least 12")
    ordered = sorted(records, key=itemgetter("name"))
    average = fmean(record["score"] for record in ordered)
    summary = f"{len(ordered)} accepted records; mean score {average:.1f}."
    lines = [fill(summary, width=width)]
    lines.extend(f'{record["name"]}: {record["score"]}' for record in ordered)
    return "\n".join(lines)

raw = [{"name": "Lin", "score": 8},
       {"name": "Ada", "points": 10},
       {"name": "Sam", "score": "oops"}]
accepted, rejected = [], []
with warnings.catch_warnings(record=True) as notices:
    warnings.simplefilter("always", LegacyPointsWarning)
    for index, record in enumerate(raw):
        try:
            accepted.append(normalize(record))
        except ValueError as error:
            rejected.append((index, str(error)))
bound = signature(render).bind(accepted, width=40)
bound.apply_defaults()
report = render(*bound.args, **bound.kwargs)
print(report)
print("warnings:", [str(notice.message) for notice in notices])
print("rejected:", rejected)

# ✅ Expected output:
# 2 accepted records; mean score 9.0.
# Ada: 10
# Lin: 8
# warnings: ['points is deprecated; use score']
# rejected: [(2, 'score must be an integer from 0 to 100')]

The incoming list stays separate from accepted normalized dictionaries. The caller captures warnings around normalization, so the validation function does not install global policy. The report is built only from accepted records; a rejected score does not silently become zero and change the mean.

Reject invalid data before selecting or averaging fields

values = [8, True, -1, 101, "10"]
accepted = [value for value in values
            if type(value) is int and 0 <= value <= 100]
print(accepted)
print(len(values) - len(accepted))

# ✅ Expected output:
# [8]
# 4

This contract requires an actual int and deliberately rejects booleans, text numbers and values outside the range. Another application may allow conversion, but that needs an explicit rule. The mean function should receive already-validated observations rather than deciding what to coerce. The statistics Module owns the assumptions behind the numerical summary.

accepted = []
if not accepted:
    raise ValueError("no accepted records")

# ✅ Expected error:
# ValueError: no accepted records

A mean of zero would be an invented observation about this empty batch. Keep “no accepted data” distinct from “accepted values averaged to zero.” The full renderer raises a clear application error before calculating a statistic.

Normalize into new records so the original evidence remains available

raw = {"name": "  Ada  ", "score": 10}
normalized = {"name": raw["name"].strip(), "score": raw["score"]}
print(normalized)
print(raw["name"] == "  Ada  ")
print(normalized is raw)

# ✅ Expected output:
# {'name': 'Ada', 'score': 10}
# True
# False

Preserving raw input helps explain a rejection or migration later. A shallow new dictionary is enough for this flat schema; it would not automatically isolate nested mutable structures. The point is a deliberate ownership contract, not a claim that copying any dictionary solves every aliasing problem.

A signature check is not a schema check

from inspect import signature

def render(records, *, width=40):
    if type(width) is not int or width < 12:
        raise ValueError("width must be an integer of at least 12")
    return len(records)

bound = signature(render).bind([{"name": "Ada", "score": 10}], width="wide")
print("binding succeeded")
try:
    render(*bound.args, **bound.kwargs)
except ValueError as error:
    print(error)

# ✅ Expected output:
# binding succeeded
# width must be an integer of at least 12

inspect confirms that width is an accepted keyword. The function still validates the value. Introspection with inspect owns binding and defaults; this integration keeps that limited guarantee separate from record and option validation.

Formatting must not change the dataset used by the statistic

from statistics import fmean
from textwrap import fill

scores = [8, 10]
summary = f"Accepted records: {len(scores)}. Mean score: {fmean(scores):.1f}."
narrow = fill(summary, width=18)
wide = fill(summary, width=60)
print(narrow)
print(wide)
print(scores)

# ✅ Expected output:
# Accepted records:
# 2. Mean score:
# 9.0.
# Accepted records: 2. Mean score: 9.0.
# [8, 10]

Wrapping changes presentation, not the scores or their meaning. Do not parse the formatted report back into data to continue processing. Keep structured records as the source of truth and regenerate text for each intended display. Text Wrapping & Formatting (textwrap) owns whitespace and width behavior.

The full project sorts by name for a stable report. The operator Module owns itemgetter; Sorting with sorted() & key owns ordering and tie policy. Neither sorting nor wrapping validates a missing score.

A deprecation is recoverable; conflicting fields are invalid

import warnings

class LegacyPointsWarning(DeprecationWarning):
    pass

def read_score(record):
    if "score" in record and "points" in record:
        raise ValueError("score and points conflict")
    if "points" in record:
        warnings.warn("points is deprecated; use score",
                      LegacyPointsWarning, stacklevel=2)
        return record["points"]
    return record["score"]

with warnings.catch_warnings(record=True) as notices:
    warnings.simplefilter("always", LegacyPointsWarning)
    print(read_score({"points": 7}))
print(len(notices))
try:
    read_score({"score": 7, "points": 9})
except ValueError as error:
    print(error)

# ✅ Expected output:
# 7
# 1
# score and points conflict

This smaller function isolates field migration; the complete normalize function also performs name, type and range validation. Do not mistake a focused demonstration for the complete schema. The warnings Module owns category/filter mechanics; the checkpoint decides which condition deserves a warning and which must fail.

Check correctness before collecting a benchmark

from timeit import Timer

scores = (8, 10)
def summary():
    return f"count={len(scores)}; total={sum(scores)}"

assert summary() == "count=2; total=18"
samples = Timer(summary).repeat(repeat=3, number=20)
print(summary())
print(len(samples))

# ✅ Expected output:
# count=2; total=18
# 3

This verifies the fragment’s result and the number of samples without claiming a portable duration or speed winner. Benchmarking with timeit owns interpreting timing experiments. A tiny report does not need a weak cache merely because weakref is available: accepted records need strong ownership until reporting finishes.

Complete the accepted-record selection

Keep only actual integers in the allowed score range, then calculate the mean and the number rejected. The literals identify the required type and the mean function.

from statistics import fmean

raw = [8, True, 10, "bad"]
accepted = [value for value in raw if type(value) is ___ and 0 <= value <= 100]
print(___(accepted))
print(len(raw) - len(accepted))

# 👉 replace ___ with int
# 👉 replace ___ with fmean

# ✅ Expected output:
# 9.0
# 2

Extend the report with explicit rejection evidence

Build a report for Jo with score 7, Mia with legacy points 5, an empty name with score 0, and Max with score True. Preserve the same validation and warning policies. Print the stable report, the migration warning and each rejected input index with its reason. Use width 32 for the summary and retain the original raw records unchanged.

import warnings
from inspect import signature
from operator import itemgetter
from statistics import fmean
from textwrap import fill

class LegacyPointsWarning(DeprecationWarning):
    pass

def normalize(record):
    name = record.get("name")
    if not isinstance(name, str) or not name.strip():
        raise ValueError("name must be nonempty text")
    if "score" in record and "points" in record:
        raise ValueError("score and points conflict")
    if "score" in record:
        score = record["score"]
    elif "points" in record:
        warnings.warn("points is deprecated; use score",
                      LegacyPointsWarning, stacklevel=2)
        score = record["points"]
    else:
        raise ValueError("score is required")
    if type(score) is not int or not 0 <= score <= 100:
        raise ValueError("score must be an integer from 0 to 100")
    return {"name": name.strip(), "score": score}

def render(records, *, width=40):
    if not records:
        raise ValueError("no accepted records")
    if type(width) is not int or width < 12:
        raise ValueError("width must be an integer of at least 12")
    ordered = sorted(records, key=itemgetter("name"))
    average = fmean(record["score"] for record in ordered)
    summary = f"{len(ordered)} accepted records; mean score {average:.1f}."
    lines = [fill(summary, width=width)]
    lines.extend(f'{record["name"]}: {record["score"]}' for record in ordered)
    return "\n".join(lines)

raw = [{"name": "Jo", "score": 7},
       {"name": "Mia", "points": 5},
       {"name": "", "score": 0},
       {"name": "Max", "score": True}]
accepted, rejected = [], []
with warnings.catch_warnings(record=True) as notices:
    warnings.simplefilter("always", LegacyPointsWarning)
    for index, record in enumerate(raw):
        try:
            accepted.append(normalize(record))
        except ValueError as error:
            rejected.append((index, str(error)))
bound = signature(render).bind(accepted, width=32)
bound.apply_defaults()
report = render(*bound.args, **bound.kwargs)
print(report)
print("warnings:", [str(notice.message) for notice in notices])
print("rejected:", rejected)

# ✅ Expected output:
# 2 accepted records; mean score
# 6.0.
# Jo: 7
# Mia: 5
# warnings: ['points is deprecated; use score']
# rejected: [(2, 'name must be nonempty text'), (3, 'score must be an integer from 0 to 100')]

Review the result by following each original index to an accepted record or a rejection. A useful integration has no silent gaps. You can extend the output format later without weakening that accounting or moving warning policy into a library function.

Practice quiz

What does this program print? values = [8, True, 10] print([value for value in values if type(value) is int])

  • [8, 10]
  • [8, True, 10]
  • [True]
  • [8]

Answer: [8, 10]. The exact-type contract rejects a boolean score despite bool being an int subclass.

What should happen when every input record is rejected?

  • Report a mean of zero
  • Report an explicit no-accepted-data condition
  • Treat rejected scores as zero
  • Use the last previous mean silently

Answer: Report an explicit no-accepted-data condition. An empty accepted dataset does not establish a numerical average.

What does this program print? from operator import itemgetter rows = [{"name": "Lin"}, {"name": "Ada"}] print([row["name"] for row in sorted(rows, key=itemgetter("name"))])

  • ['Lin', 'Ada']
  • ['Ada']
  • ['Ada', 'Lin']
  • ['Lin']

Answer: ['Ada', 'Lin']. The selector supplies the name used for stable alphabetical reporting.

Why does the renderer validate width after signature binding?

  • Binding always converts strings to integers
  • Binding checks only return values
  • Binding makes validation unnecessary
  • Binding checks call shape, not option semantics

Answer: Binding checks call shape, not option semantics. A permitted keyword can still hold an invalid value.

What does this program print? from statistics import fmean print(fmean([8, 10]))

  • 9.0
  • 18.0
  • 2
  • 0.0

Answer: 9.0. Only accepted observations enter the mean.

Where should a library function normally install a caller-specific ignore policy?

  • Permanently at import time
  • It should emit a meaningful warning and let the caller choose the policy
  • Inside every unrelated utility
  • In the record dictionary

Answer: It should emit a meaningful warning and let the caller choose the policy. Separating emission from disposition avoids hiding unrelated application warnings.

What does this program print? raw = {"name": " Ada ", "score": 10} clean = {"name": raw["name"].strip(), "score": raw["score"]} print(raw["name"] == " Ada ") print(clean["name"])

  • False Ada
  • True Ada
  • True Ada
  • False Ada

Answer: True Ada. Creating a normalized dictionary preserves the raw evidence.

What should be established before comparing report-generation timings?

  • That one function has fewer lines
  • That the shortest sample looks impressive
  • That a weak cache exists
  • That both implementations produce the same required result

Answer: That both implementations produce the same required result. A speed comparison between different or incorrect outputs does not answer the intended question.

Continue this course

Related lessons