When to use assert

Chris Angelico rosuav at gmail.com
Wed Oct 22 18:01:17 CEST 2014


On Thu, Oct 23, 2014 at 2:49 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Chris Angelico wrote:
>
>> And at that point, the assertion is redundant, on par with:
>>
>> a = len(seq)
>> assert isinstance(a, int)
>>
>> because you shouldn't have to assert what's part of a function's
>> guarantee.
>
> That depends on how well you trust the function, how paranoid you are, and
> whether you wish to include a checked comment, among other considerations.
> I'd prefer to write the above than:
>
> a = len(seq)
> # At this point, a is an int.
>
> because comments inside code that aren't checked are technically known
> as "lies" <http://import-that.dreamwidth.org/956.html>. Ha ha only serious.
> ...
> Checking the post-condition of a built-in like len() is too paranoid for my
> tastes...
>
> As I wrote:
>
>     This is why assert can be divisive. Since we can vary in our
>     confidence about the correctness of code, one person's useful
>     assertion may be another person's useless runtime test.

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)?

This is the job of a test suite. 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.

Or is that insufficiently paranoid?

ChrisA



More information about the Python-list mailing list