liveBook · Manning

Assertion

As explained in Software Design for Python Programmers

An assert statement evaluates a condition and aborts execution when the condition is false.

An assert statement checks a condition and immediately aborts execution when the condition is false. It enforces a function’s precondition at the point where the function is called. section 6.3.2

Protecting a circular buffer

A CircularBuffer.remove() method asserts that the buffer is not empty before removing a value. Calling remove() on an empty buffer therefore ends execution with an assertion failure instead of corrupting head, tail, or count state. An application may raise an exception instead when the caller should handle invalid use. section 6.3.2

How Software Design for Python Programmers covers it

How deep it goes
Defines the check and its aborting behavior, while deferring exception handling as an alternative contract.
Examples
Uses an empty CircularBuffer and an unchecked remove() call to demonstrate assertion failure.
What you can do after
Diagnose/debug with it: detect violated preconditions immediately instead of allowing invalid state to propagate.
How it connects
Connects preconditions with programming by contract, assertion failures, and exceptions.

Also explained in

Compare how 15 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.