The Assert Keyword In Python



  • 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_


  • 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 – assert() example

import math


class Circle:

    radius = 0

    area   = 0


    def __init__(self, radius):

        self.radius = radius


    def color(self):


        print("coloring done")


    def area(self):

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


redCircle           = Circle(5)






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

is thrown.

Traceback (most recent call last):

  File "", line 19, in <module>


  File "", line 11, in color





Copyright 2022 ©