Python @ DjangoSpin

Python: Asserting values using assert keyword

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Asserting values using assert keyword in Python

Asserting values using assert keyword in Python

It's hard to argue with the fact that all practical programs have bugs. It is better to find them beforehand and strangle them before they bother the testing team. A developer tries to minimise the occurrence of these defects, by writing self-checks to ensure that things are going as he plans. The assert statement helps to achieve this purpose. The assert statement takes an expression and if it is true, it continues the program flow. Else, it raises an AssertionError. Let's take a look at an example.

>>> def squareIt(number):
    assert type(number) is int
    return number * number
 
>>> squareIt(9)
81
>>> squareIt('a')
Traceback (most recent call last):
    squareIt('a')
    assert type(number) is int
AssertionError

Assertions serve as safety nets, providing a way to check that the state of the program is as per the expectations of the developer. The developer might have some assumptions as he is writing the code, which can be made explicitly obvious with assert statements. This is in conformance with the Zen of Python, which states that "Explicit is better than implicit."

The assert statement takes an optional second option, which can be used to give an elaborate explanation of the failure detected. This can also include cleanup code.

>>> def squareIt(number):
    assert type(number) is int, "Please input a number"
    return number * number
 
>>> squareIt('a')
Traceback (most recent call last):
    squareIt('a')
    assert type(number) is int, "Please input a number"
AssertionError: Please input a number

Bear in mind that assertions are not a substitute for the raise keyword. The user has an option to ignore the assertions by executing the Python script with -O flag in the command prompt.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply