TactivergeLite

Lite / Building Machines That Respond / Week 8

Catch bad data before it bites

A data logger writes ERR whenever its sensor hiccups. Should your program crash, skip the line, or quietly count it as zero?

About 40 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Real logs contain blank lines, error codes and impossible values. A program that crashes on the first one is useless; a program that silently turns them into zeros is dangerous. Defensive checks make software that keeps working and tells you the truth about its data.

Predict

A log line is -999.0, a common 'no reading' code. What does float("-999.0") do?

  1. Raises a ValueError
  2. Returns -999.0
  3. Returns None
Guess first, then reveal

It returns -999.0: it is a perfectly valid number. Only a range check (is it between −40 and 125 °C?) can reject it. Conversion checks and plausibility checks catch different problems.

Discover

In the Code Lab, type parse_reading from this lesson and run it on the sample lines. Then add your own nasty lines (" 21.5 ", "21,5", "nan", "1e3") and predict what each does before running. Which ones slip through, and how would you stop them?

What the interactive shows (text version)

The Code Lab exercise can be traced by hand. parse_reading returns the number for '21.5' and '22.1'; None for 'ERR' and '' (float fails); and None for '-999.0' (outside −40 to 125). So good = [21.5, 22.1] and 3 of 5 lines are rejected. ' 21.5 ' converts (float ignores surrounding spaces) and '21,5' fails.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch how try and except catch a specific error, and why catching only the error you expect is safer than catching everything.

How try and except let a program handle bad input, such as a malformed line in a log, without crashing.

“Python Tutorial: Using Try/Except Blocks for Error Handling” by Corey Schafer (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

Validate every line

def parse_reading(line):
    """Return the reading in °C, or None if the line is not a plausible reading."""
    try:
        value = float(line)
    except ValueError:
        return None
    if value < -40 or value > 125:
        return None
    return value

lines = ["21.5", "ERR", "", "-999.0", "22.1"]
good = []
for line in lines:
    value = parse_reading(line)
    if value is not None:
        good.append(value)
print(good)    # [21.5, 22.1]

Two different checks

The conversion check (try / except ValueError) catches lines that are not numbers at all: ERR, blanks, '--'. The plausibility check catches numbers that cannot be real: −999.0, 130.5. The band comes from the sensor's datasheet (here −40 to 125 °C, typical of small temperature sensors) or from physics.

Never hide the evidence

Count what you reject and report it: '3 of 480 lines rejected'. Never replace bad lines with 0, which drags the mean down and looks like a real reading. Catch only the error you expect (except ValueError), not every error, so genuine bugs still show up.

Explain it another way

Intuitive

A bouncer at a door: first check it is a ticket at all, then check it is for tonight. People without one are turned away and counted, not let in as 'nobody'.

Technical

try / except handles a specific exception locally; the function's contract (return a float or None) is documented in the docstring. Validation at the boundary keeps the rest of the program working on clean, typed data.

Applied

Industrial and scientific data pipelines always have this stage, often called input validation or data cleaning, and keep counts of rejected records as a health signal for the sensors.

Worked example 1

What does parse_reading do with "nan"?

float("nan") succeeds and returns nan (not a number). Both nan < -40 and nan > 125 are False, so the range check lets it through! Add import math and if math.isnan(value): return None, or write the range check as if not (-40 <= value <= 125): return None, which rejects nan because the chained comparison is False.

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

readings

Practice 2. Which check rejects the line "130.5" from a sensor rated −40 to 125 °C?
Practice 3. Why is replacing bad lines with 0 a bad idea?
Practice 4. Why write except ValueError rather than a bare except?

Apply it

Extend parse_reading to reject nan, then write four asserts (a good line, ERR, blank and −999.0). Use it in your log program and print how many lines were rejected out of the total.

Reflect

What would you want to happen if 30 % of a log's lines were rejected? Should the program still report a mean?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Reproduce, hypothesise, test: hunting logic bugsPlan the sensor-log checker →