When to use assert
Roy Smith
roy at panix.com
Sun Nov 17 08:33:48 EST 2013
In article <528871d5$0$29975$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> * Don't use assert for any error which you expect to recover from.
> In other words, you've got no reason to catch an AssertionError
> exception in production code.
Which leads to another reason for using asserts...
Every once in a while, I'll get into a situation where something is
happening that I just can't understand. If a given pice of code is
being called, there's NO WAY the program should be exhibiting the
behavior it's exhibiting. But, there's also NO WAY that piece of code
can't be getting called.
So, I stick "assert 0" in the code an re-run the program to see if I get
an AssertionError. If I do, then I know the code is being run. If I
don't then I know it's not. Either way, I know more about what's going
on than I did before. Once I know what's going on, I remove the assert.
More information about the Python-list
mailing list