Concepts / Defensive Programming Practices

Defensive Programming Practices

Defensive programming means checking important assumptions before the program relies on them.

  • Programming

A Check Before the Next Step

Defensive programming means checking important assumptions before the program relies on them. In Python, the assert statement is a development and debugging tool for this purpose. It verifies that a condition is true. If the condition is true, execution continues silently. If the condition is false, Python raises an AssertionError immediately.

Imagine that later code assumes a list contains at least one item. An assertion can verify that assumption at the point where it matters. This helps reveal the exact place where the program state stopped matching the developer's expectation.

assert conditionevaluate conditionTrueNext statementFalseAssertionErrorcondition is truepass silentlycondition is falseraise immediately
What happens next when an assert condition evaluates to true versus false?

Tracing a List Assumption

Worked example

Verifying that a list is nonempty

A program expects a list to contain at least one element. Verify that assumption before the program continues.

  1. 1
    Create the state

    The list contains one element, so its length is at least 1.

  2. 2
    Evaluate the condition

    The assertion checks whether the list length is at least 1. The condition is true.

  3. 3
    Continue execution

    Because the condition is true, the assertion passes silently and the next statement can run.

Result

The assertion produces no output or error when the list has one element.

python
Output
The assumption holds

The important point is not that assert prints a confirmation. A passing assertion is silent. Its job is to stop execution only when the checked assumption is false.

Assertion Failure in Execution

When Python encounters assert, it first evaluates the condition. A false condition causes Python to raise an AssertionError immediately. The program halts at that point, so statements after the failed assertion do not run. The traceback identifies the line containing the failed assertion, pinpointing where the assumption was violated.

python
Output
AssertionError
Evaluate conditionFalseAssertionErrorExecution stopscondition is falseraise immediatelyremaining statements do not run
How does a failed assertion interrupt normal program execution and produce an AssertionError?
Programassert len(items) >=1AssertionErrorLater statementsreachescondition is falseexecution does not reach
At which point in program execution does a failed assertion stop the remaining statements from running?

Making Failures Informative

An assert statement has a required keyword and condition. The condition can be any boolean expression. You can optionally add a comma followed by a message string. When the assertion fails, Python includes that message in the AssertionError output, making the violated assumption easier to understand.

python
assertverification keywordconditionboolean expression,optional separatormessageoptional explanationfollowed bycan be followed byintroduces
What is the difference between assert condition and assert condition, message?

Practical Boundaries

Assertions are intended for development and debugging. They help catch logic errors and verify assumptions about program state. They are not a replacement for proper exception handling when the program must handle expected runtime errors.

  • Common mistake

    Using an assertion as the main handling mechanism for an expected runtime error

    What it looks like

    Using assert to handle a condition that normal program input may regularly violate

    Why it fails

    Assertions are development and debugging tools, not substitutes for proper exception handling in production code.

    Do this instead

    Use assertions to verify assumptions and use appropriate exception handling for expected runtime errors.

  • Common mistake

    Relying on an assertion for production-critical logic

    What it looks like

    Assuming a required safety check will always run because it is written as assert condition

    Why it fails

    Assertions can be disabled with Python's -O flag.

    Do this instead

    Keep critical production logic independent of assertions.

  • Common mistake

    Leaving a failed assertion without useful context

    What it looks like
    assert len(items) >= 1
    Why it fails

    The failure identifies an AssertionError, but it does not explain why the assumption mattered.

    Do this instead

    Add a descriptive message after a comma when extra context would help debugging.

  • Common mistake

    Expecting a passing assertion to display confirmation

    What it looks like

    Expecting output after a true assertion

    Why it fails

    A true assertion passes silently.

    Do this instead

    Treat the absence of output or error as the normal result of a passing assertion.

Check Your Reasoning

EASY

A program expects a list to contain at least one element. Write an assertion that checks this assumption and includes a message explaining the failure. Then state what happens to the next statement when the list is empty.

Hints
  • Use the list length as the condition.
  • Place a comma and a descriptive message after the condition.
  • A false condition raises AssertionError and stops execution at the assertion.

What do you think happens?

Suppose the list is empty and the assertion checks whether its length is at least 1. What happens to the statement immediately after the assertion?

  • It runs normally

  • It runs only after the error message is printed

  • It does not run because an AssertionError is raised

Reveal answer
Answer:

It does not run because an AssertionError is raised.

Python evaluates the condition, raises AssertionError when the condition is false, and halts execution at that point.

Key Takeaways

  1. 1
    assert verifies that a boolean condition is true.
  2. 2
    A true assertion passes silently and execution continues.
  3. 3
    A false assertion raises AssertionError immediately and stops execution at that line.
  4. 4
    A comma followed by a message makes a failed assertion more informative.
  5. 5
    Use assertions for development and debugging, not for production-critical logic or expected runtime error handling.

At a glance

  • Use assert to verify assumptions about program state during development and debugging.
  • Python evaluates the assertion condition before continuing.
  • A false condition raises AssertionError and prevents later statements from running.
  • Add a descriptive message after a comma to clarify the violated assumption.
  • Do not rely on assertions for production-critical checks because Python can disable them with the -O flag.

More concepts starting with D