On 12/03/2021 10.26, Cameron Simpson wrote: > On 12Mar2021 05:31, Chris Angelico <ros...@gmail.com> wrote: >> On Fri, Mar 12, 2021 at 3:37 AM Serhiy Storchaka <storch...@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 read this, and @Chris' points, am wondering if I'm missing a/the point:- (Scenarios 1 and 2, plus leaving the asserts to run in case of 'accidents' during production-execution) When testing the integrity of some collection of data, why use assert over raising a descriptive and class-identified exception? Both can be trapped by 'higher-level' code. Both can provide text-planations. Is assert so much faster/cheaper than try...except...raise? -- -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list