Why assert is not a function?

Cameron Simpson cs at cskk.id.au
Thu Mar 11 16:26:42 EST 2021


On 12Mar2021 05:31, Chris Angelico <rosuav at gmail.com> wrote:
>On Fri, Mar 12, 2021 at 3:37 AM Serhiy Storchaka <storchaka at gmail.com> wrote:
>> assert(expensive_computation())
>
>Do you have any asserts like that, or is that a purely theoretical
>complaint? I have never once seen anything that costly - usually it'll
>be something like checking a length (and this isn't C's strlen, since
>Python can get lengths of all built-in types quickly), or some simple
>checks.

That's very much in the eye of the beholder. Usually my asserts are 
pretty cheap. But there are two scenarios where they accrue significant 
cost.

Scenario 1 is where I'm maintaining some data structure, possibly with 
fiddly corner cases. That associated class may have a self_check method 
to verify integrity, and that can land in an assertion. Potentially 
quite expensive.

Scenario 2 is the performance critical function which nonetheless is 
complicated (or just... long). I've written a few of these and littering 
the code with asserts becomes necessary to check correctness, 
particularly if you're modifying it. Not everything lends itself to unit 
tests - we often want to be assured of things in the middle of a 
process.

In scenario 2, each assert is pretty cheap, but their cumulative effect 
has a significant performance impact. Being able to turn them off 
altogether is a distinct real world win.

(To those crying "break it up", sometimes that is hard because of the 
embodied state, and sometimes that is unwanted because of the 
performance impact (function calls aren't free and neither is the 
packaging-into-parameters needed to turn an operation into a function 
call); for 99% of code both of these are cheap enough, but in this niche 
they're a problem.

>Having assert be a function would not make it much harder to get rid
>of. It would just make it harder to get the text.

Hah. I repeat my mention of the ycecream package - very neat!

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list