I love assert

Marko Rauhamaa marko at pacujo.net
Wed Nov 12 16:41:08 EST 2014


Anton <anton.schattenfeld at gmail.com>:

> I am not sure how and when you use assert, but something that stops me
> from using assert is that in many cases I would use them to
> 1) Check type of an incoming argument/returned value
> 2) Check value of an incoming argument/returned value

You use asserts to boldly state that the asserted condition never fails.
If it should fail anyway, the world could come tumbling down and you
would hang your head in shame.

Asserts help the reader of the code understand why some possibilities
are not considered by the code. They are not considered because the
writer of the code asserts they are not really possible.

Asserts help not only lay the blame to the writer of the code but might
also make it easier to troubleshoot failures.

I use asserts sparingly, just like comments (which asserts are). I use
them to communicate nonobvious truths to the future maintainer of the
code.

For example, instead of

     # never reached

I will write

     assert False


Or I might indicate the exhaustion of possibilities:

     if status == OK:
         ...
     elif status == ERROR:
         ...
     else:
         assert status == WARNING
         ...


Marko



More information about the Python-list mailing list