[Python-ideas] Raise exception if (not) true

Steven D'Aprano steve at pearwood.info
Thu Feb 20 22:28:30 CET 2014


On Thu, Feb 20, 2014 at 09:44:57PM +0100, spir wrote:

> But I would like to be able to add an error type to assertions (in addition 
> to the optional message). This is particularly useful for people (like me) 
> who systematically check func inputs (for client debugging comfort), using 
> assert's. 

Then your code is systematically broken, and badly so. All anyone needs 
to do to disable your checking is pass -O to the Python interpreter.

assert is not a short-cut for lazy programmers to avoid having to write 
an explicit "if cond: raise SomethingAppropriate(message)". Assertions 
have specific uses. You should read this post I made last November:

https://mail.python.org/pipermail/python-list/2013-November/660401.html


> It would be mainly ValueError and TypeError.
> 
> Example:
>     assert x > 0, "x should be positive", ValueError

-1

Apart from the optimization-disables-asserts issue, this breaks the 
readers expectation for what assertions are used for and what they will 
do. Here, you are actually using an assert for a critical piece of error 
checking, but you are disguising it as a checked comment or piece of 
less critical defensive programming.


-- 
Steven


More information about the Python-ideas mailing list