Assertions are bad, m'kay?
steve+comp.lang.python at pearwood.info
Sat Mar 8 15:44:23 CET 2014
On Fri, 07 Mar 2014 16:15:36 -0800, Dan Stromberg wrote:
> On Fri, Mar 7, 2014 at 3:11 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Assertions are not bad! They're just misunderstood and abused.
>> You should read this guy's blog post on when to use assert:
> Nice article.
> BTW, what about:
> if value >= 3:
> raise AssertionError('value must be >= 3')
The error message is misleading. But you've probably noticed that by
What about it? Since it's missing any context, it could be a good use of
an exception or a terrible use. Where does value come from? Why is there
a restriction on the value?
As I see it, there are likely two reasons for writing such a test:
1) You're testing a value that comes from the user, or some
library you don't control; or
2) You're testing some internal invariant, a contract between
two parts of your own code, a piece of internal logic, etc.
In the first case, I don't think you should raise AssertionError. A
ValueError would be more appropriate.
In the second case, using an assert might be better, since that gives you
the opportunity to remove it at compile-time, if you choose.
More information about the Python-list