The assert keyword in Python

assert is a keyword in Python.The assert() statement accepts a Boolean Condition as its parameter and halts the execution with an AssertionError if the expression evaluates to False.

Keywords Updated 26 Dec 2017 2 min read

Overview

  • Python provides an assert statement for the developers to make sure the program invariants are correct during the testing and development of the program.

  • assert is a keyword in python.

  • Python assert, accepts a Boolean expression and the execution is stopped with an AssertionError when the Boolean expression evaluates to false.

  • The assert statements will be translated only if __debug__ is enabled. That is when there is no optimization using the command line option –O, has been requested for.

  • The assert statements will be skipped in the optimized python code.

Through assert statement the programmer verifies the program correctness

Courtesy: Windy_

Example

  • The example is a trivial class, assume it is reasonably bigger and significant class and the criticality requires more than one developer to work on this class on the same day.

  • Unless the developer who writes method color()makes sure that area is calculated correctly , the coloring will be beyond the boundaries of the circle or will not cover enough till the boundary.

  • Even if such class is developed and or managed by one developer at a time it is always good for the developer to make the invariants of the circle object valid at all the times.

  • Thus in ensuring program correctness the assert statement is an essential tool for the developer.

python
#Python – assert() example

import math

class Circle:

    radius = 0

    area   = 0

    def __init__(self, radius):

        self.radius = radius

    def color(self):

        assert(self.area==2*math.pi*self.radius)

        print("coloring done")

    def area(self):

        self.area = 2*math.pi*self.radius

redCircle           = Circle(5)

#redCircle.area()

redCircle.color()

Output

Since the function call redCircle.area()is commented, area is not calculated for the instance redCircle due to which an AssertionError

is thrown.

python
Traceback (most recent call last):

  File "assert_ex.py", line 19, in <module>

    redCircle.color()

  File "assert_ex.py", line 11, in color

    assert(self.area==2*math.pi*self.radius)

AssertionError