Python Assert

The assert statement in Python is a debugging tool used to test conditions that must be true at a program’s execution time. The assert raises an AssertionError when the condition is false; the error message is optional. This helps in catching bugs and ensuring that the program is working as intended.

Syntax

assert condition, message
  • condition: This is a Boolean expression. If this evaluates to True, then the program continues execution. If it evaluates to False, then an AssertionError is raised.
  • message: This is an optional argument. If given, it will be shown in the error message that appears when the assertion fails.

How It Works

  1. Python evaluates the condition.
  2. If the condition is True then the program continues to run.
  3. If the condition is False:
    • An AssertionError is thrown.
    • The optional message (if supplied) is added to the error.

Example 1: Basic Usage

x = 10
assert x > 0, "x must be positive"
print("Assertion passed, x is positive")

Output:

Assertion passed, x is positive

Here, x > 0 is True, so the program continues without any issue.

Example 2: When Assertion Fails

x = -5
assert x > 0, "x must be positive"

Output:

AssertionError: x must be positive

Since x > 0 is False, an AssertionError is raised with the message “x must be positive”.

Why Use assert?

  1. Debugging: assert is used mainly to catch bugs during development. It helps check assumptions and makes sure that the state of the program is as expected.
  2. Validation: You can use assert to validate inputs or intermediate results.

Enabling and Disabling Assertions

  • Assertions are enabled by default in Python.
  • They can be disabled globally by running Python in “optimized mode” using the -O flag.
python -O your_script.py

When Python runs in optimized mode:

  • All assert statements are ignored.
  • This can be useful in production environments where performance is critical.

Limitations of assert

  1. Not for Production Validation:
  • Do not use assert for input validation or critical checks in production. Assertions may be disabled, so are not guaranteed to run.
  • Use exceptions like ValueError or custom exception handling for production use.

2. Performance:

  • While assertions are useful at development time, they add overhead. Use them only in production when performance does not matter.

Example: Debugging with assert

def divide(a, b):
    # Ensure the denominator is not zero
    assert b != 0, "Denominator cannot be zero"
    return a / b

print(divide(10, 2))  # This works fine
print(divide(10, 0))  # Raises AssertionError

Summary

  • The assert statement is useful when debugging and catching logical errors.
  • It should not be used for production input validation.
  • Use it to document and enforce assumptions in code during development.