DEV Community

Cover image for The Power Of Python's Assert Statement
Justice Cofie
Justice Cofie

Posted on

The Power Of Python's Assert Statement

What Are Assertions In Python?

In Python, assertions are statements that allow developers to test the correctness of their code. If the assertion evaluates to true, nothing happens; otherwise, an AssertionError is raised.

Let's look at how assertions are used in Python first, but first let's create a Book class. Below is an example Python code.

from typing import NamedTuple

class Book(NamedTuple):
    author: str
    title: str
    published_year : int
Enter fullscreen mode Exit fullscreen mode

We created a Book class that inherits from the typing module's NamedTuple class. Because NamedTuples are tuples by default, our Book class is immutable.
Creating an instance of the Book class

>>> book1 = Book('Christian Mayer', 'The Art Of Clean Code', 2022)
>>> book1
Book(author='Christian Mayer', title='The Art Of Clean Code', published_year=2022)
Enter fullscreen mode Exit fullscreen mode

Let's use the assert statement to test for the truthiness of the published_year.

>>> assert(book1.published_year == "2022")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>>
Enter fullscreen mode Exit fullscreen mode

AssertionError was raised because the published_year has an integer type and we tested it against a string.

Now let's test it with a valid year value of 2022

>>> assert(book1.published_year == 2022)
>>>
Enter fullscreen mode Exit fullscreen mode

Because, the assertion statement is true nothing happened

Why Use Assertions?

  • As a debugging aid rather than an error handling mechanism
  • As internal self-checks for a program
  • Allows developers to find the likely root cause of a bug more quickly

Top comments (0)