[Python-ideas] PEP 531: Existence checking operators

Paul Moore p.f.moore at gmail.com
Sat Oct 29 05:54:06 EDT 2016


On 29 October 2016 at 07:21, Nick Coghlan <ncoghlan at gmail.com> wrote:
> A short-circuiting if-else protocol for arbitrary "THEN if COND else
> ELSE" expressions could then look like this:
>
>     _condition = COND
>     if _condition:
>         _then = THEN
>         if hasattr(_condition, "__then__"):
>             return _condition.__then__(_then)
>         return _then
>     else:
>         _else = ELSE
>         if hasattr(_condition, "__else__"):
>             return _condition.__else__(_else)
>         return _else
>
> "and" and "or" would then be simplified versions of that, where the
> condition expression was re-used as either the "THEN" subexpression
> ("or") or the "ELSE" subexpression ("and").
>
> The reason I think this is potentially interesting in the context of
> PEPs 505 and 531 is that with that protocol defined, the
> null-coalescing "operator" wouldn't need to be a new operator, it
> could just be a new builtin that defined the appropriate underlying
> control flow:

This seems to have some potential to me. It doesn't seem massively
intrusive (there's a risk that it might be considered a step too far
in "making the language mutable", but otherwise it's just a new
extension protocol around an existing construct). The biggest downside
I see is that it could be seen as simply generalisation for the sake
of it. But with the null-coalescing / sentinel checking use case, plus
Greg's examples from the motivation section of PEP 335, there may well
be enough potential uses to warrant such a change.

Paul


More information about the Python-ideas mailing list