When to use assert

Dan Stromberg drsalists at gmail.com
Wed Oct 22 18:18:24 CEST 2014

On Wed, Oct 22, 2014 at 9:01 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Oct 23, 2014 at 2:49 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Chris Angelico wrote:
> I agree that the assert is preferable to the comment. But maybe my
> level of paranoia is just lower than most people's, as I wouldn't
> bother checking the post-conditions of pretty much anything. Do you
> put these assertions every time you call the function? Every time
> you're depending on its return value? At what point should you stop
> writing Python code and start using a language with a lot more
> boilerplate and checking (I believe Haskell fits that, though I'm not
> overly familiar with the language)?

I like to use assertions and "if cond: raise ValueError('foo')" a lot.

I think Eiffel may be the poster-child for a language with
pre-conditions, post-conditions and assertions.

I think you're in good company - a lot of developers don't use assertions much.

I like assertions, because they tend to stop bugs pretty quickly.  If
you have 3 functions, one calling another calling another, assertions
in each can keep you from having to backtrack among them when
debugging, instead going directly to the problem's source.

> This is the job of a test suite.

Test suites are great, and I can't really question your reliance on
them.  I love having lots of automated tests.  But for the reason I
described above, I still like having lots of assertions.

> You don't pepper your code with
> assertions to the effect that "I just pushed something onto my queue,
> it should now have this item in it"; you create a test case for it,
> and verify your function there. In the rest of the code, you trust
> that your test suite passes, and don't waste time with assertions.

I wouldn't test that a value was added to a queue immediately after
adding it.  That's excessive, and may even require an abstraction

But if, for example, I have a string with 3 known-good values, I'll
if/elif/elif/else, and make the else raise an AssertionError.  The
assertion should never fire, but if the code changes, it could, and if
there's a typo somewhere, it could then too.

> Or is that insufficiently paranoid?

With good tests, you're probably fine.

More information about the Python-list mailing list