Assertions and preconditions

Stating what a function assumes and what it guarantees: precondition, postcondition, invariant, the assert statement and its failure, defensive programming, and the difference with checking an input.

  • 26 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Precondition: what is it?

    Show the answer

    A condition that must hold when a function is called for it to be sure to work properly.

    It binds the caller: if racine(n) assumes n >= 0, the caller must not pass it -4.

  • What does this program print?

    ```python
    def racine(n):
    assert n >= 0, "n must be zero or more"
    return n ** 0.5

    print(racine(9))
    print(racine(-4))
    print("end")
    `

    • 3.0, then AssertionError: n must be zero or more, without end
    • 3.0, then the computation of (-4) ** 0.5 runs, then end is displayed
    • 3.0, n must be zero or more, then end
    • 3.0, then a ValueError raised on the return line
    Show the answer

    3.0, then AssertionError: n must be zero or more, without end

    assert raises AssertionError with the message when the condition is false, and nothing runs after it: neither the return nor print("end"). The stop happens at the assertion's line, not in the computation.

  • A … must hold before the call, a … is guaranteed afterwards.

    Show the answer

    A precondition must hold before the call, a postcondition is guaranteed afterwards.

    Together they form the function's contract: if the caller meets the precondition, the function guarantees the postcondition.

  • Postcondition: what is it?

    Show the answer

    A condition the function guarantees about its result when it finishes, provided its preconditions were met.

    It binds the function: for trier(t), the result holds the same elements as t, in ascending order.

  • A program asks the user for an age and passes it to a function that assumes age >= 0. What should be done with the input?

    • Check it with an if and ask again
    • Write assert age >= 0 and let the program stop if the user makes a mistake
    • Check nothing: the function's precondition is enough to protect the program
    • Replace any negative value with 0 without warning
    Show the answer

    Check it with an if and ask again

    A faulty input is an expected case: it is handled with an if and a message. The assertion guards against programming errors, and Python can ignore it with the -O option.