Reaching out to capture a moment

For reasons that are a mystery to me, my local NOAA weather station has started reporting wind gusts of “0.0” miles per hour, which makes both my NerdTool desktop and my little iPhone weather app report silly looking results.

Gusts up to 0.0 mph

The code that gathers the weather data from NOAA and presents it is kept in this GitHub repository. The part that deals with wind speeds and gusts has always been able to handle a situation in which the station doesn’t report gusts at all:

python:
try:
  gust = ', gusting to %s mph' % noaa['wind_gust_mph']
except KeyError:
  gust = ''
out.append('Wind: %s at %s mph%s' % ( noaa['wind_dir'], noaa['wind_mph'], gust))

Unfortunately, the try/except form can’t catch gusts of zero because they aren’t errors, at least not by Python’s definition. The fix was pretty simple:

python:
try:
  if float(noaa['wind_gust_mph']) > 0:
    gust = ', gusting to %s mph' % noaa['wind_gust_mph']
  else:
    gust = ''
except KeyError:
  gust = ''
out.append('Wind: %s at %s mph%s' % ( noaa['wind_dir'], noaa['wind_mph'], gust))

This corrected what showed up on my Desktop. I made a similar change in the CGI program to keep 0.0 mph gusts out of the weather page.

You may be wondering why I didn’t use Python’s ternary operator. In fact, that’s what I did first, but I decided that this

python:
try:
  gust = ', gusting to %s mph' % noaa['wind_gust_mph'] if float(noaa['wind_gust_mph']) > 0 else ''
except KeyError:
  gust = ''
out.append('Wind: %s at %s mph%s' % ( noaa['wind_dir'], noaa['wind_mph'], gust))

wasn’t as easy to read as the explicit if/else block, so I changed it.

I’ve always thought the ternary operator—which looks like

ruby:
x = x > 0 ? 1 : -1

in Ruby, Perl, and other C-derived languages, and like

python:
x = 1 if x > 0 else -1

in Python—is pretty cool because it reads very much like you’d say it: “Set x to positive one if it’s positive and negative one otherwise.”1 But when the assignment or the test get long, the simple intent of the assignment gets lost in the details, and the more formal multiline if/else structure is much clearer.

The foregoing is, I confess, more simplistic than my usual programming posts. It was really just an excuse to use the title (originally “Bending down to give me a rainbow”) and to include this video. Don’t leave before the 1:40 mark.


  1. This is not a good signum definition because it doesn’t handle zero correctly.