Skip to content

05. Functions — Mini-project

The marketing team receives a JSON export of customer records every week. Each week, an analyst copies the same loops into a notebook to answer the same questions: how much did customers spend, which plan spends most, who are the best customers, and which records are incomplete?

Write a script, customer_report.py, that answers these questions with a toolkit of small functions. Each function does one job, has a Google-style docstring and can be reused in next week’s script. The script runs with one command: python customer_report.py.

The project uses every part of module 05: function definitions and return values, defaults, keyword-only parameters, **kwargs forwarding, a closure, key functions with sorted() and max(), a higher-order grouping function and recursion over nested JSON.

data/customers.json holds 20 customer records (C00001 to C00020). The top level is a dict with three keys: exported_at, count and customers. Each record has this shape:

{
"customer_id": "C00001",
"name": "Ana Silva",
"email": "ana.silva@example.com",
"signup_date": "2018-12-01",
"plan": "premium",
"address": {"street": "546 Park Blvd", "city": "Chicago", "region": "North",
"postal_code": "81790"},
"tags": ["mobile_app", "referral"],
"orders": [{"order_id": "O000614", "date": "2023-02-18", "items": 1, "amount": 32.0}],
"phone": "+1-555-908-5284"
}

The sample shows only the first of Ana Silva’s five orders. The orders are real orders from data/sales.csv (up to the first 5 per customer), and amount is the order revenue in USD. The file has quirks on purpose, so your code must be defensive:

  • 3 customers have an empty orders list.
  • 5 customers have an empty tags list.
  • 2 addresses have no postal_code key at all.
  • phone is null for one customer, present for six and absent for the rest.

Load it with the two lines from the lesson. Module 07 explains them.

import json
with open("data/customers.json", encoding="utf-8") as f:
data = json.load(f)

Your script must define these functions. Each one has a Google-style docstring.

  1. find_values(obj, key): recursive; returns every value stored under key at any depth of dicts and lists.
  2. find_nulls(obj, path=""): recursive; returns the paths of all None values, such as customers[9].phone.
  3. get_path(obj, path, *, default=None): reads a dotted path such as "address.postal_code"; returns default when a key is missing.
  4. total_spend(customer): the sum of a customer’s order amounts, rounded to cents. Use find_values.
  5. summarize(values, *, digits=2): returns a dict with count, total, mean and max. For an empty list, mean and max are None.
  6. make_tier(*, gold, silver): a factory that returns a closure. The closure maps a spend to "gold" (at least gold), "silver" (at least silver), "bronze" (more than 0) or "none".
  7. group_by(records, key): a higher-order function; returns a dict that maps key(record) to the list of records with that value.
  8. report(customers, *, gold=1500, silver=500, top=3, **summary_options): prints the full report and forwards summary_options to every summarize call.

The script must also:

  • Keep all printing inside report. Every other function returns a value.
  • Print the plans and tiers in a fixed order, so the report is the same every week for the same data.
  • Handle an empty group: a plan with no customers next week shows - as its mean instead of crashing.
  • End with at least four assert checks on the toolkit functions.

With the default options, the report must be exactly:

Expected output
Customer report: 20 customers, 48 orders
Total spend: 13,711.70 USD (mean 685.59 per customer)
Spend by plan
basic n=7 total 5,629.30 mean 804.19
standard n=7 total 3,895.34 mean 556.48
premium n=6 total 4,187.06 mean 697.84
Tiers (gold >= 1500, silver >= 500)
gold 3 C00003, C00017, C00019
silver 7 C00001, C00002, C00006, C00011, C00015, C00018, C00020
bronze 7 C00004, C00005, C00007, C00009, C00010, C00014, C00016
none 3 C00008, C00012, C00013
Top 3 customers
C00017 Mateo Lopez 2,324.98 USD
C00003 Mei Chen 2,070.07 USD
C00019 Ravi Patel 1,763.46 USD
Data quality
no orders: C00008, C00012, C00013
no postal_code: C00005, C00014
null values: customers[9].phone
  1. Explore the data in the REPL. Load the file and look at data["customers"][0]. Check len(data["customers"]) and the keys of one order.

  2. Write the recursive helpers. Start with find_values, then find_nulls. Test them on a tiny literal first, such as {"a": [{"amount": 1}, {"amount": 2}]}, before you run them on the file.

  3. Write get_path. Split the path with partition("."). Remember to forward default in the recursive call.

  4. Write the metric functions. total_spend uses find_values. summarize must not divide by zero for a customer group with no orders.

  5. Write the closure. make_tier(gold=1500, silver=500) returns a function of one argument. Test it on 2,000, 600, 21.5 and 0.

  6. Write group_by. It takes a key function, just like sorted(). Use it for the plans (key=lambda c: c["plan"]) and for the tiers (key=lambda c: tier(total_spend(c))).

  7. Write report. Build each section from the helpers. Rank customers with sorted(..., key=total_spend, reverse=True).

  8. Add the asserts and run python customer_report.py. Compare each line with the expected report. Then try report(customers, digits=0) and check that the option reaches summarize.

A skeleton to start from:

customer_report.py (starter)
"""customer_report.py: spend and data-quality report for data/customers.json."""
import json
def find_values(obj, key):
"""Return every value stored under key, at any depth of dicts and lists."""
# TODO: recursive case for dicts, for lists; base case returns []
def find_nulls(obj, path=""):
"""Return the paths of all None values inside obj."""
# TODO
# TODO: get_path, total_spend, summarize, make_tier, group_by, report
with open("data/customers.json", encoding="utf-8") as f:
data = json.load(f)
customers = data["customers"]
report(customers)
# TODO: at least four assert checks
Criterion Points Full points when
Runs as a script 2 python customer_report.py runs with no error
Correct report 3 Every line equals the expected report
Recursion 3 find_values, find_nulls and get_path recurse, with clear base cases, and handle empty lists and missing keys
Parameter design 2 digits, default, gold, silver and top are keyword-only; **summary_options is forwarded unchanged
Higher-order functions and closures 2 make_tier returns a closure; group_by and sorted take key functions
Pure functions 2 Only report prints; no function changes its arguments or a global variable (reading module-level constants is fine)
Docstrings 1 Every function has a Google-style docstring with a one-line summary
Self-checks 1 At least four meaningful assert statements
Total 16 13 or more: you are ready for module 06
  1. Add a by_region section: group the customers by address.region with get_path and show the total spend per region.
  2. Add months_since(date_text, *, today="2025-01-02") that returns the whole months between two ISO dates, and report the customers whose last order is more than 12 months old.
  3. Make report return the lines as a list instead of printing them, and print them in the main part of the script. Then write an assert that checks one line of the report.
  4. Add a tiers option: let report accept tiers={"gold": 1500, "silver": 500} and build the closure from the dict with make_tier(**tiers).
  5. Write find_values without recursion, with an explicit list as a stack of objects still to visit. Compare the two versions for clarity.

Try the project yourself first. Then compare your script with this one. Your names and docstrings can differ; your report must not.

Reference solution
customer_report.py
"""customer_report.py: spend and data-quality report for data/customers.json."""
import contextlib
import io
import json
PLANS = ("basic", "standard", "premium")
TIERS = ("gold", "silver", "bronze", "none")
def find_values(obj, key):
"""Return every value stored under key, at any depth of dicts and lists.
Args:
obj: Parsed JSON: a dict, a list or a leaf value.
key: The dict key to look for.
Returns:
A list of the values found, in document order.
"""
found = []
if isinstance(obj, dict):
for k, value in obj.items():
if k == key:
found.append(value)
found.extend(find_values(value, key))
elif isinstance(obj, list):
for item in obj:
found.extend(find_values(item, key))
return found # base case: a leaf has nothing inside
def find_nulls(obj, path=""):
"""Return the paths of all None values inside obj.
Args:
obj: Parsed JSON.
path: The path of obj in the whole document; "" at the top.
Returns:
A list of paths such as "customers[9].phone".
"""
if obj is None: # base case: a null value
return [path]
if isinstance(obj, dict):
children = [(f"{path}.{k}" if path else k, v) for k, v in obj.items()]
elif isinstance(obj, list):
children = [(f"{path}[{i}]", v) for i, v in enumerate(obj)]
else: # base case: any other leaf
return []
paths = []
for child_path, value in children:
paths.extend(find_nulls(value, child_path))
return paths
def get_path(obj, path, *, default=None):
"""Return the value at a dotted path such as "address.postal_code".
Args:
obj: A nested dict.
path: Keys joined by dots.
default: The value to return when a key on the way is missing.
Returns:
The value at the path, or default.
"""
if not isinstance(obj, dict):
return default
head, _, rest = path.partition(".")
if head not in obj:
return default
if not rest:
return obj[head]
return get_path(obj[head], rest, default=default)
def total_spend(customer):
"""Return the sum of a customer's order amounts, rounded to cents."""
return round(sum(find_values(customer, "amount")), 2)
def summarize(values, *, digits=2):
"""Summarize a list of amounts.
Args:
values: A list of numbers; may be empty.
digits: Decimal places for total and mean.
Returns:
A dict with count, total, mean and max; mean and max are None if empty.
"""
if not values:
return {"count": 0, "total": 0, "mean": None, "max": None}
return {
"count": len(values),
"total": round(sum(values), digits),
"mean": round(sum(values) / len(values), digits),
"max": max(values),
}
def make_tier(*, gold, silver):
"""Return a function that maps a spend in USD to a tier name.
Args:
gold: The minimum spend for "gold".
silver: The minimum spend for "silver".
Returns:
A function tier(spend) -> "gold", "silver", "bronze" or "none".
"""
def tier(spend):
if spend >= gold:
return "gold"
if spend >= silver:
return "silver"
if spend > 0:
return "bronze"
return "none"
return tier
def group_by(records, key):
"""Return a dict that maps key(record) to the list of records with that value.
Args:
records: Any list of items.
key: A function of one item that returns a group label.
Returns:
A dict of label -> list of items, in first-seen order.
"""
groups = {}
for record in records:
groups.setdefault(key(record), []).append(record)
return groups
def money(value):
"""Return value as "1,234.56", or "-" when value is None."""
return "-" if value is None else f"{value:,.2f}"
def report(customers, *, gold=1500, silver=500, top=3, **summary_options):
"""Print the weekly spend and data-quality report.
Args:
customers: The list of customer records.
gold: The minimum spend for the gold tier.
silver: The minimum spend for the silver tier.
top: How many top customers to list.
**summary_options: Forwarded to summarize(), for example digits=0.
"""
spends = [total_spend(c) for c in customers]
overall = summarize(spends, **summary_options)
orders = find_values(customers, "order_id")
print(f"Customer report: {len(customers)} customers, {len(orders)} orders")
print(
f"Total spend: {overall['total']:,.2f} USD "
f"(mean {overall['mean']:,.2f} per customer)"
)
print("\nSpend by plan")
by_plan = group_by(customers, key=lambda c: c["plan"])
for plan in PLANS:
group = [total_spend(c) for c in by_plan.get(plan, [])]
s = summarize(group, **summary_options)
print(
f" {plan:<9} n={s['count']:<2} "
f"total {money(s['total']):>9} mean {money(s['mean']):>8}"
)
print(f"\nTiers (gold >= {gold}, silver >= {silver})")
tier = make_tier(gold=gold, silver=silver)
by_tier = group_by(customers, key=lambda c: tier(total_spend(c)))
for name in TIERS:
ids = [c["customer_id"] for c in by_tier.get(name, [])]
print(f" {name:<7} {len(ids):>2} {', '.join(ids)}")
print(f"\nTop {top} customers")
for c in sorted(customers, key=total_spend, reverse=True)[:top]:
print(f" {c['customer_id']} {c['name']:<13} {total_spend(c):>9,.2f} USD")
print("\nData quality")
no_orders = [c["customer_id"] for c in customers if not c["orders"]]
no_postal = [
c["customer_id"]
for c in customers
if get_path(c, "address.postal_code") is None
]
print(" no orders: ", ", ".join(no_orders))
print(" no postal_code: ", ", ".join(no_postal))
print(" null values: ", ", ".join(find_nulls({"customers": customers})))
with open("data/customers.json", encoding="utf-8") as f:
data = json.load(f)
customers = data["customers"]
report(customers)
# --- Self-checks ---------------------------------------------------------
assert len(find_values(data, "amount")) == 48
assert total_spend(customers[0]) == 1325.54
assert summarize([]) == {"count": 0, "total": 0, "mean": None, "max": None}
assert make_tier(gold=1500, silver=500)(21.5) == "bronze"
assert get_path(customers[4], "address.postal_code", default="?") == "?"
assert find_nulls({"a": [1, None], "b": None}) == ["a[1]", "b"]
assert money(None) == "-" and money(1234.5) == "1,234.50"
# An empty group must not crash: capture the printed report of a list
# with no premium customers (module 11 explains `with` and redirect_stdout).
with contextlib.redirect_stdout(io.StringIO()) as buffer:
report([c for c in customers if c["plan"] != "premium"])
assert "premium n=0 total 0.00 mean -" in buffer.getvalue()
Output
Customer report: 20 customers, 48 orders
Total spend: 13,711.70 USD (mean 685.59 per customer)
Spend by plan
basic n=7 total 5,629.30 mean 804.19
standard n=7 total 3,895.34 mean 556.48
premium n=6 total 4,187.06 mean 697.84
Tiers (gold >= 1500, silver >= 500)
gold 3 C00003, C00017, C00019
silver 7 C00001, C00002, C00006, C00011, C00015, C00018, C00020
bronze 7 C00004, C00005, C00007, C00009, C00010, C00014, C00016
none 3 C00008, C00012, C00013
Top 3 customers
C00017 Mateo Lopez 2,324.98 USD
C00003 Mei Chen 2,070.07 USD
C00019 Ravi Patel 1,763.46 USD
Data quality
no orders: C00008, C00012, C00013
no postal_code: C00005, C00014
null values: customers[9].phone

Run it from the project folder:

Terminal
python customer_report.py

How it works:

  1. Recursion. find_values and find_nulls walk any mix of dicts and lists. Their base cases are the leaves. find_nulls builds the path on the way down, with .key for dicts and [i] for lists, so each problem has an exact address. get_path removes one key per call.
  2. Defensive metrics. total_spend is 0 for an empty orders list, because sum([]) is 0. summarize returns None for the mean of an empty group instead of dividing by zero, and money prints that None as -, so a plan with no customers cannot crash the report.
  3. Closure. make_tier(gold=1500, silver=500) returns tier, which remembers both limits. report builds it once from its own options, so a caller can change the tiers with report(customers, gold=2000).
  4. Higher-order functions. group_by takes a key function, like sorted(). The same function groups by plan and by tier; only the lambda changes.
  5. Parameter design. All options are keyword-only, so report(customers, 2000) is an error instead of a silent change. **summary_options reaches every summarize call: report(customers, digits=0) rounds every total and mean to whole dollars, and the report then shows them as 13,712.00.
  6. Fixed order. PLANS and TIERS give the sections a stable order. A dict built from the data would list the plans in the order of the file, which can change from week to week.
  7. Self-checks. The asserts pin down the edge cases that the report alone does not show: an empty list, a missing key, nulls inside lists and a report with an empty plan.

Alternative: pandas does the grouping and the sums in a few lines after pd.json_normalize(customers, record_path="orders", meta=["customer_id", "plan"]) (module 24). The function toolkit is still worth having: it works without dependencies, and each function is easy to test.