Edge Case Handling

Concepts covered: Guard Clauses

A function that works on the inputs its author pictured is half finished. Pipelines hand functions empty batches, missing values, strings where numbers were expected and lists of a single row. An edge case is an input at the boundary of what the function was written for, and each one either gets a deliberate answer or produces a crash or a silent wrong number.

Where an unguarded function breaks

What does this program print?

def average(values):
    return sum(values) / len(values)

print(average([4, 8, 6]))
print(average([]))

Empty is only one boundary. The table lists the inputs worth asking about for any function that takes a list of numbers, with what this average function does with each.

Input kindExampleWhat average does
Empty`[]`ZeroDivisionError
None`None`TypeError from `sum`
Wrong container`"468"`TypeError from `sum`
Bad item`[4, "8", 6]`TypeError from `sum`
Single item`[7]`7.0, correct
Booleans`[True, False]`0.5, counted as 1 and 0 without complaint

Guard clauses that return a deliberate answer

A guard clause checks for a bad case at the top of the function and returns immediately. The design question is what to return. For an average of nothing, 0 would be a lie: a dashboard would plot 0 minutes for a listener with no data, and nobody downstream could tell it from a real 0. None says 'no answer exists' and forces the caller to check with is None.

def average(values):
    if not isinstance(values, list):
        return None
    if len(values) == 0:
        return None
    return sum(values) / len(values)

print(average([4, 8, 6]))
print(average([]))
print(average(None))
print(average("468"))

Output:

6.0
None
None
None

isinstance(None, list) is False, so the first guard catches None along with strings and dicts. The order of guards matters: each check must be safe to run on whatever the earlier checks let through. Put the len check first and average(None) crashes with TypeError: object of type 'NoneType' has no len() before the type check ever runs.

Bad items inside a good list

A type check on the list says nothing about its items. A batch of watch times may carry a string that was never converted, or a None where a client failed to report. The function faces a policy choice: reject the whole batch, or skip the bad items. Skipping keeps the pipeline moving, but a silent skip hides data loss, so the version below returns the count of dropped items alongside the average.

def average_minutes(values):
    if not isinstance(values, list):
        return None, 0
    total = 0
    good = 0
    skipped = 0
    for v in values:
        if isinstance(v, int):
            total += v
            good += 1
        else:
            skipped += 1
    if good == 0:
        return None, skipped
    return total / good, skipped

print(average_minutes([30, "45", 60, None]))
print(average_minutes(["x"]))
print(average_minutes(None))

Output:

(45.0, 2)
(None, 1)
(None, 0)

The final guard, good == 0, catches a case the type checks cannot: a real list in which every item was bad. Without it, ["x"] reaches total / good and divides by zero, the empty-list crash arriving by a different road.

Do
  • Decide the return value for empty, None and wrong-type input before writing the main logic
  • Order guards so each check is safe on what earlier checks let through
  • Report how many items were skipped instead of dropping them silently
  • Test every function on [], None and a 1-item list
Avoid
  • Return 0 for 'no data' when 0 is also a real answer
  • Call len() on a value that may be None
  • Assume a list of the right type holds items of the right type
  • Guard only the case that crashed last week

About this lesson

This section is part of the Problem Solving: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.