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

Ivan Pozdeev vano at mail.mipt.ru
Mon Nov 27 21:12:36 EST 2017

The `assert' statment was created the same as in previous languages like 
C/C++: a check to only do in debug mode, when you can't yet trust your 
code to manage and pass around internal data correctly. Examples are 
array bounds and object state integrity constraints.

Unlike C, Python does the aforementioned checks all the time, i.e. it's 
effectively always in "debug mode". Furthermore, validation checks are 
an extremily common use case.

I have been using assert in my in-house code for input validation for a 
long time, the only thing preventing me from doing the same in public 
code is the fact that it only raises AssertionError's while library code 
is expected to raise TypeError or ValueError on invalid input.

The last drop that incited me to do this proposition was 
where none of the _seven_ answer authors (beside me) managed to make a 
_single realistic use case_ for `assert' as a debug-only check.


So, I'm hereby proposing to:

* make `assert' stay in optimized mode
* change its syntax to raise other types of exceptions

E.g.: "assert condition, type, value" or "assert condition, type, 
exception_constructor_argument(s)" to maintain backward compatibility.


More information about the Python-ideas mailing list