Proposal: runtime validation statement

F. GEIGER f.geiger at vol.at
Mon Jul 12 05:56:53 EDT 2004


Paul Rubin wrote:

> I frequently find myself writing stuff like
> 
>     # compute frob function, x has to be nonnegative
>     x = read_input_data()
>     assert x >= 0, x               # mis-use of "assert" statement
>     frob = sqrt(x) + x/2. + 3.
> 
> This is not really correct because the assert statement is supposed to
> validate the logical consistency of the program itself, not the input
> data.  So, for example, when you compile with optimization on, assert
> statements become no-ops.  And yet, it's generally desirable to
> validate input whenever you can, and raising an exception is
> frequently the right thing to do with bad data.  A function like
> 
>     class ValidationError(Exception): pass
>     def _validate(cond, message):
>        if not cond: raise ValidationError, message
> 
> takes care of it, of course, so it's slightly redundant to add a
> special statement like
> 
>     validate x >= 0, (x, "must not be negative")
> 
> which works exactly like assert but raises a different exception and
> is never optimized away.  But the same can be said of the print
> statement (use sys.stdout.write or a print function instead) and for
> that matter the addition operator (use "x - (-y)" instead of x+y), the
> bool type (use 1 and 0 instead of True and False), etc.
> 
> We have to conclude that choosing what statements the language
> supports is not just a matter of making things possible, but also of
> steering what the common idioms should be.  Using a user-defined
> function to check input means a couple more program-specific things to
> remember (the function itself and the exception class it raises),
> clutters up the code, etc.  And so I've come to feel that a "validate"
> statement (maybe with some different keyword) like the above is in the
> Pythonic spirit and should be considered for some forthcoming release.
> 
> Thoughts?

I use assert to protect my software from me, i.e. to catch programming 
errors, e.g. to catch cases where I called a method the wrong way. If 
this can happen under production consitions too, then it's a user error, 
not a programming error.

So, I use raise to protect my software from user errors.

Your sample seems to be a case of the latter, i.e. you have to write 
some sort of exception handling anyway. Issuing an error message 
anywhere in your code might not be what you really want.

Kind regards
Franz GEIGER




More information about the Python-list mailing list