Assert

Contents

Assert#

Assert statement allows us to do sanity checks in our code. It is also a very handy tool in preventing bugs that do not throw an Error. Consider the following factorial function:

def fact(n):
    result = 1
    for i in range(n):
        result*=i
    return result
fact(-1)
1

What if \(n = 1.5\), \(n = -1\) or \(n \) is not a numeric type? Our function is defined for non-negative integers only. However, for some of those invalid inputs, the function can actually return something! assert is a great feature to add here:

def fact(n):
    assert n is int and n >=0
    result = 1
    for i in range(n):
        result*=i
    return result
fact(-1)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-0ca68cd43ada> in <module>
      5         result*=i
      6     return result
----> 7 fact(-1)

<ipython-input-9-0ca68cd43ada> in fact(n)
      1 def fact(n):
----> 2     assert n is int and n >=0
      3     result = 1
      4     for i in range(n):
      5         result*=i

AssertionError: 

Now our program throws an AssertionError and we immediately know that the input is invalid. While in this simple example such precautions might seem to be an overkill, assert scales very well. When multiple functions exchange data, this feature might shorten the debugging time a lot. If you do not want your program to crash because of the AssertionError surround your code with the try..except block:

def fact(n):
    try:
        assert n is int and n >=0
        result = 1
        for i in range(n):
            result*=i
        return result
    except AssertionError:
        print("This is an invalid input")

fact(-1)
This is an invalid input

In some coding regimes, assert is considered acceptable only in the development process. It is often deactivated in the final version of the software.

Exercises#

  • Perimeter of a circle Define a function which calculates the perimeter of a circle given its radius.

HINT: import math for the value of \(\pi\). Do not assume that r is of any particular type.