Facing up to mistakes

INPUT · Slides

Write your assumptions down

01 / 07

An assumption you do not write down disappears

While you are writing code your head is always full of assumptions about how things stand at a given point.

"A price is never negative." "The list is not empty." But those assumptions are written nowhere in the code, so when one of them turns out to be false, nobody notices.

The tool for writing them down is assert, which means to state something flatly.

02 / 07

The shape of an assert

After assert you write the condition you want to hold. That is all there is to it.

If the condition holds, the line passes straight through and does nothing. Nothing appears on screen. Silence is what success looks like.

price = 300assert price > 0print("all good")

Result

all good

03 / 07

Get it wrong and it stops there

When the condition does not hold, Python raises an AssertionError and stops on the spot. None of the lines after it run.

Stopping is the useful part. Not letting a wrong value travel any further is the whole job of assert.

price = -100print("checking")assert price > 0print("never reached")

Result

checking
AssertionError

04 / 07

Add a message

Put a comma after the condition and you can add a message. It comes out alongside the error when the condition fails.

Write what was supposed to be true, and of what. Leave a line for the version of you who reads this later.

price = -100assert price > 0, "price should be positive"

Result

AssertionError: price should be positive

05 / 07

It is aiming at something different from if

You could write the same test with an if. But the two are aiming at completely different things.

  • if … handles what can happen. Stock at zero, an empty name. You write what to do about it
  • assert … states what should not be able to happen. If it does, the program is wrong

What goes in an assert is your certainty that "by the time we are here, this holds without question".

count = 2assert count >= 1, "count should be at least 1"print(count * 150)

Result

300

06 / 07

Do not wrap it in brackets

Here is the common mistake: assert (price > 0, "price should be positive"), with the condition and the message bundled together inside brackets.

Written that way, Python takes the contents as one single value, and that value holds true whatever happens. So you have checked nothing at all, while believing you have.

The condition and the message go side by side after a comma, with no brackets round them. That is the one thing to remember.

07 / 07

To sum up

assert is for writing your own assumptions into the code.

  • if it holds, it passes straight through
  • if it fails, an AssertionError stops things on the spot
  • a message goes after the comma

But stopping is all assert can do. Sometimes you want to carry on down another road rather than stop. That is next.