8/34
Part 3 of 8 · BatchesLearn and do

One bad table doesn't stop the batch

Catch the error per table, and put it in that table's slot

Now many tables, one per day, through the same steps. Tuesday's table has only two columns, because a sensor was offline:

monday = [[21, 19, 23], [25, 18, 24]]
tuesday = [[20, 22], [19, 21]]
wednesday = [[23, 20, 30], [22, 21, 25]]

The obvious loop is [apply(t, steps) for t in tables]. With [("sort", 2)], it raises ValueError: no column 2 in a table 2 wide at Tuesday. Monday's finished result is lost with it, and Wednesday never runs. On a batch of ten thousand files, one bad file would cost you all of them.

So catch per table, and put what went wrong where the result would have gone:

def run_batch(tables, steps):
    check(steps)
    results = []
    for table in tables:
        try:
            results.append(apply(table, steps))
        except Exception as error:
            results.append(error)
    return results

On the three days with [("sort", 2)], each table gets its own slot in the result:

TableShapeIts slot in the result
monday2 x 3[[21, 19, 23], [25, 18, 24]]
tuesday2 x 2ValueError('no column 2 in a table 2 wide')
wednesday2 x 3[[22, 21, 25], [23, 20, 30]]

Result i belongs to table i, so the caller needs no ids to match them up. isinstance(result, Exception) tells a failure from a table.

Keep the exception itself, not None. It says what went wrong, and the caller can log it, retry that table or raise it. Some codebases return (ok, value) pairs instead. Either works, as long as the failure keeps its reason.

A map step that divides by a zero reading works the same way. It gives ZeroDivisionError('division by zero') in that table's place, and the other tables come out normally.

Catch Exception, not everything, so Ctrl-C still stops the batch

Predict

Is KeyboardInterrupt, what Ctrl-C raises, a kind of Exception?

Pick an answer above to see the rest