Why assert is not a function?

Richard Damon Richard at Damon-Family.org
Fri Mar 12 08:09:42 EST 2021


On 3/12/21 12:31 AM, Chris Angelico wrote:
> On Fri, Mar 12, 2021 at 3:53 PM Cameron Simpson <cs at cskk.id.au> wrote:
>> For me, try/except is for when something might reasonably "go wrong" in
>> normal use, even niche normal use. Whereas assert is for things which
>> should _never_ occur. Roughly, again for me, try/except if for catching
>> misuse and assert is for catching misdesign/misimplementation.
> Something like that, yeah. An assertion failure represents a bug *in
> this code*, something that shouldn't ever happen. If it's possible to
> trigger the failure with some other piece of code (calling something
> with bad arguments, or whatever), then assert is the wrong tool for
> the job. Similarly, if you find yourself catching AssertionError
> anywhere outside of unit testing, something is horribly wrong
> somewhere :)
>
> ChrisA

Chris, I would disagree with that statement. An assert says that there
is something wrong with THE code, not THIS code. It is perfectly
reasonable, and good defensive programming, to assert on the
per-conditions to the procedure at its beginning.

Now, it may be true that a 'friendlier' procedure may be defined to
check some of these and return an error, but that then locks that
behavior into the API, so the cost of the check becomes an absolute
requirement.

In langauges like C, the assert for this may be more important because
the language provides more opportunity for 'undefined behavior'.

It is reasonable to skip the input assert if it becomes too expensive
for benefit it provides, or if something else will catch the error. This
likely actually applies to a lot of Python code, so it may seem that it
doesn't apply.

-- 
Richard Damon



More information about the Python-list mailing list