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

smarie sylvain.marie at schneider-electric.com
Tue Jan 16 11:25:52 EST 2018

Thanks Paul

Le mardi 16 janvier 2018 16:56:57 UTC+1, Paul Moore a écrit :
> > Why does this need to be a statement at all? Unlike assert, it's 
> > always executed, so it can be defined as a simple function

Very good point. Actually that's what I already provide in valid8 with the assert_valid 
function. See all examples here 

Let's consider this example where users want to define on-the-fly one of 
the validation functions, and combine it with another with a 'or':

    assert_valid('surface', surf, or_(lambda x: (x >= 0) & (x < 10000), is_foo_compliant), help_msg="surface should be 0=<x<10000 or foo compliant")

How ugly for something so simple ! I tried to make it slightly more compact 
by developping a mini lambda syntax but it obviously makes it slower. 
Anyway it becomes

    assert_valid('surface', surf, or_((x >= 0) & (x < 10000), is_foo_compliant), help_msg="surface should be between 0 and 10000 or foo compliant")
    or even (if you pre-convert Is_foo_compliant to mini_lambda)
    assert_valid('surface', surf, ((x >= 0) & (x < 10000)) | Is_foo_compliant), help_msg="surface should be between 0 and 10000 or foo compliant")

There are three reasons why having a 'validate' statement would improve 

 * no more parenthesis: more elegant and readable
 * inline use of python (1): no more use of lambda or mini_lambda, no 
performance overhead
 * inline use of python (2): composition would not require custom function 
composition operators such as 'or_' (above) or mini-lambda composition 
anymore, it could be built-in in any language element used after <validate>

resulting in 

        validate (surf >= 0) & (surf < 10000) or is_foo_compliant(surf), "surface 
should be 0=<x<10000 or foo compliant"

(I removed the variable name alias 'surface' since I don't know if it 
should remain or not)

Elegant, isn't it ?

> I don't see how a validate statement avoids having to deal with all of 
> > the complexity you mention here. 

It would obviously need to be quite smart :) but it is possible, since I 
can do it with assert_valid today.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180116/4ddd3b66/attachment-0001.html>

More information about the Python-ideas mailing list