Proposal: runtime validation statement

Dave Brueck dave at pythonapocrypha.com
Mon Jul 12 11:08:03 EDT 2004


Paul Rubin wrote:
[snip]
> 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?

Agreed!

I usually end up subclassing Exception and writing a validation function 
like you show above. At first I liked the fact that a module threw a 
module-specific family of exceptions that could be caught downstream, 
but after having used this approach for some time I've come to the 
conclusion that the vast majority of the time the exceptions thrown are 
of the generic "ValidationError" variety, and that having them defined 
in a module-specific way added no value. By extension, the validation 
function itself adds no value and is just a nuisance.

Also, a developer-defined function doesn't stand out as well as a 
statement would - a statement sets it apart from normal function calls 
which are doing the actual work to solve the problem at hand - and it'd 
be easy for syntax-highlighting editors to color it differently too.

IMO 'validate' isn't too bad a choice for a keyword. Sorta long but it's 
quick to type.

-Dave



More information about the Python-list mailing list