I love assert

Marko Rauhamaa marko at pacujo.net
Thu Nov 13 00:23:08 CET 2014


Chris Angelico <rosuav at gmail.com>:

> Or, in as many cases as possible, raise an implicit KeyError and save
> yourself a lot of typing. Any time these kinds of elif trees can be
> turned into dict lookups, you get non-assert error checking for free.

I agree that you shouldn't sprinkle asserts around the code. But
consider this example:

     count = next_size / len(choices)

The casual reader of the code might be left wondering if "choices" could
be zero-length and if the programmer had overlooked the possibility,
leading to a lengthy analysis and bewilderment.

However, the programmer could have played this frustration out already
in his head and written:

     assert len(choices) > 0
     count = next_size / len(choices)

or, equivalently:

     # here len(choices) > 0
     count = next_size / len(choices)

and the casual maintainer would be able to read on.


Marko



More information about the Python-list mailing list