[Python-ideas] Repurpose `assert' into a general-purpose check

Jason Maldonis jjmaldonis at gmail.com
Mon Nov 27 21:49:40 EST 2017


>
> Assertions should not be used as shorthands for "if cond: raise Exc"
> in the general case.
>


I'm just a lurker and usually I agree with why the suggested features
shouldn't be implemented, but I actually might chime in to pitch this one a
bit more -- and I think it can be done nicely without breaking backward
compatibility.

As a scientist, I like assert statements for two reasons: 1) you can
disable them to speed up the code, and 2) it's how we think as scientists.

Consider these two pieces of code, and which one you'd prefer to read:

if not condition:
    raise ValueError

assert condition:
    raise ValueError

As a scientist, I prefer the second one because I naturally read it as:
"condition is true, therefore ..." and I can predict the next step of the
algorithm naturally by filling in the "..." in my mind.  It makes the
assumptions of the code a bit more explicit than the code `if not
condition:`, which I must think about and to translate to "the
condition must be true" before I can continue reading.

That, in addition to being able to disable the assert statements, makes me
like and use them a reasonable amount. However, every time I do use them, I
always think "crap, when this breaks I'm going to have to come back here
and read my code/comments because the error message isn't very helpful",
and that makes me not want to write assert statements.  So I like writing
them because while I'm writing/reading the code, they make sense, but I
don't like reading their error message output because it isn't useful to me
as a user/developer.

I realize this is very minor, but I actually really like it, and I think
the below syntax would be pretty nice and backwards compatible:

assert condition:
    raise ValueError

Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171127/7e6557fb/attachment.html>


More information about the Python-ideas mailing list