Assertions: Make Internal Assumptions Checkable

When you write a program, you rely on facts about its internal state: a count should stay nonnegative, an index should identify an existing element, or two totals should agree. An assertion is an executable check that a condition expected to hold is true at a particular point. Assertions make these expectations visible and can expose a disagreement close to where it becomes observable. The examples here use Python.

State the expected condition

Python provides this form:


Python
assert condition, "diagnostic message"


The condition is a predicate. With assertions enabled, a true condition allows execution to continue. A false condition raises AssertionError. The optional message helps explain the expectation that failed; it does not repair the state or supply a replacement value.


Write the condition as the fact you expect, rather than the error you want to detect. For example, if an internal counter must stay between zero and a capacity, including both endpoints, write:


Python
assert 0 <= count <= capacity, "count outside capacity"


A passing assertion establishes only the condition it actually checks. Checking that a count is nonnegative does not establish that it is the correct count.


An enabled assertion either continues execution or signals a failed condition.


Place checks where facts become known

An invariant is a property expected to hold at designated points during execution. For a job divided into completed and remaining tasks, a useful count invariant is:


completed+remaining=planned\text{completed} + \text{remaining} = \text{planned}


You can check this relationship after an update has finished:


Python
assert completed + remaining == planned, "task count mismatch"


Example: A job contains 12 tasks. After an update, the program records 7 completed tasks and 5 remaining tasks. The sum is 12, so this assertion passes. If the program instead records 6 remaining tasks, the sum is 13 and the check fails.


Placement matters. A check before a calculation can verify an assumption needed by that calculation. A check afterward can verify an expected result. During a multi-statement update, a relationship might temporarily be false; place the check where the relationship is supposed to have been restored.



Keep checks safe to remove

Python can omit assertions when running in optimized execution. Therefore, required program behaviour must not depend on an assertion running.


Situation

Appropriate approach

Reason

An internal update should preserve a count relationship

Assert the relationship after the update

A failure exposes an unexpected internal state

A user may enter an unacceptable value

Perform explicit input validation

Rejection must remain active when assertions are omitted

A calculation must update stored data

Perform the update outside the assertion

Removing a check must not remove required work


Avoid conditions with a side effect, such as removing an item or modifying a list. Compute the result with ordinary statements, then assert a property of that result. Diagnostic messages should also avoid changing state; they are evaluated only when an enabled assertion fails.



What to remember

  • Assert the condition that should be true at that point.
  • Check an invariant where the program is expected to preserve it.
  • Keep required validation and state changes outside assertions.
  • Interpret a failure as evidence about an expectation, not proof of the mistake's exact location.

Example: Check a Warehouse Allocation

Example: A warehouse planner allocates whole items from a stock of 42 items. Its internal plan requests 13 items. The stock invariant requires the remaining count plus the allocated count to equal the starting stock. Assume all arguments are integers, available is nonnegative, assertions are enabled, and no failure handling surrounds the call.


A developer writes this function:


Python
def allocate(available, requested):
    assert 0 <= requested <= available, "request outside internal plan"
    remaining = available + requested
    assert remaining + requested == available, "stock count mismatch"
    return remaining


a) For allocate(42, 13), which assertion fails, and what values reach that check?


First check the request. Both comparisons hold because 13 is nonnegative and does not exceed 42. Execution therefore reaches the calculation of remaining.


The current calculation produces ________:


remaining=42+13=55 items\text{remaining} = 42 + 13 = 55\ \text{items}


The left side of the stock check then totals ________:


remaining+requested=55+13=68 items\text{remaining} + \text{requested} = 55 + 13 = 68\ \text{items}


The check compares 68 with 42, so its condition is false. The second assertion fails with the message stock count mismatch; the function does not return a value normally. The check exposes the inconsistent update but does not correct it.


b) Repair the stock calculation and determine the result of the same call.


Allocating items reduces available stock, so replace the addition with subtraction:


Python
remaining = available - requested


Calculate the corrected remaining count:


remaining=42−13=29 items\text{remaining} = 42 - 13 = 29\ \text{items}


Now verify the stock invariant using the corrected value:


29+13=42 items29 + 13 = 42\ \text{items}


The request check and the stock check both pass. The repaired function returns 29, representing 29 remaining items. This agrees with the practical expectation that allocating a positive number reduces the stock.


c) Using the repaired function, what happens for allocate(42, 47)?


Evaluate the first assertion before attempting the stock update. The lower comparison, zero less than or equal to 47, is true. The upper comparison, 47 less than or equal to 42, is ________. The chained condition is therefore false.


The first assertion fails with the message request outside internal plan. Execution stops before the stock calculation, so this call never computes a remaining count or reaches the second assertion. The request violates the internal plan's stated bound; no negative stock result is returned.

A scheduler stores integer values in used and limit, with limit positive. At this point, its internal rule allows used to equal zero or limit. Which assertion checks exactly that allowed range?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each term used when reasoning about runtime checks and error signalling with the description that fits it. Each description is used exactly once.

Match each term
A.

An except block that catches a matching error type and decides how the program continues

B.

A guarantee about the result or state that must be true when a function returns

C.

An object raised to signal an error condition that a caller may catch and recover from

D.

A requirement on the inputs or state that must be true when a function is called

E.

A property of a data structure that stays true before and after every operation on it

F.

A runtime check of an internal assumption that holds whenever the code is correct, so a failure means a bug

Exception handler

Precondition

Exception

Invariant

Postcondition

Assertion

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A dispatch program checks the following assertion with assertions enabled. Each table row represents a separate execution using item counts. Enter Pass or Fail for each row, considering only the condition shown.


Python
assert shipped + remaining == initial, "item count mismatch"
ExecutionInitial itemsShipped itemsRemaining itemsAssertion result
W601743
X601744
Y35350
Z35034

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice