[Python-ideas] Specify an alternative exception for "assert"
Guido van Rossum
guido at python.org
Mon May 2 11:54:44 EDT 2016
On Mon, May 2, 2016 at 8:38 AM, Ryan Gonzalez <rymg19 at gmail.com> wrote:
> I feel like you just brought up the exact issue. Assertions should *never*
> be used for things like this. Because, one day, some stupid idiot is going
> to use assertions to perform some sort of data validation, someone else
> will use that library with -O, and the world will explode.
>
> That's a very strong opinion, and a bit of a doomsday scenario. I hear
worries about this a lot, but I've never heard a story from someone to whom
this actually happened.
> It's just far too attractive to use but far too easy to misuse.
>
The thing is, assert exists and is not going away. People are writing these
asserts today (there are still many in asyncio). In many cases the assert
is not guarding against bad data or user input, but simply against a
confused caller. The assumption is that once the program is debugged enough
to go to production (where you use -O) the need for the asserts has gone
down enough that it doesn't matter the checks are gone -- the confused call
site has long been found during tests and fixed.
> And, if you really want:
>
> if my_cond: raise MyError('abc')
>
> Compare that to:
>
> assert my_cond, MyError('abc')
>
There's a bug in your example, and that bug is a good argument for using
assert: the equivalent of that assert should be
if not my_cond: raise MyError('abc')
and that extra inversion often makes the code a little less
straightforward. Compare
if times < 1: raise ValueError()
to
assert times >= 1: raise ValueError()
The latter states positively what we're expecting. This is much more
helpful for the reader.
Also, RPython uses assertions for error handling. Trust me, dealing with
> that is *not* fun.
>
RPython is not Python; isn't that a feature? :-)
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160502/f24a8bd6/attachment.html>
More information about the Python-ideas
mailing list