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

Paul Moore p.f.moore at gmail.com
Tue Jan 16 12:01:01 EST 2018

I fixed the reply-to this time, looks like you're still getting messed
up by Google Groups.

On 16 January 2018 at 16:25, smarie
<sylvain.marie at schneider-electric.com> wrote:
> 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.

Why do you do this? What's the requirement for delaying evaluation of
the condition? A validate statement in Python wouldn't be any better
able to do that, so it'd be just as ugly with a statement. There's no
reason I can see why I'd ever need delayed evaluation, so what's wrong
with just

    assert_valid(0 <= surf < 10000 and is_foo_compliant(surf),
help_msg="surface should be 0=<x<10000 or foo compliant")

> There are three reasons why having a 'validate' statement would improve
> this:
>  * 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"

So how will that work any differently than the function version I gave
above? In terms of the language syntax, it would just be

    validate EXPR, EXPR

and the first EXPR will be evaluated as a boolean, and if it's false
an exception will be raised with the second expression as the message.
There's no delayed evaluation involved, so a function would work
exactly the same.

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

No more so than my function version, but yes far more so than yours...


More information about the Python-ideas mailing list