[Python-ideas] Null coalescing operator
Sven R. Kunze
srkunze at mail.de
Wed Nov 2 13:32:22 EDT 2016
On 02.11.2016 17:17, Nick Coghlan wrote:
> The gist is that rather than writing the bare:
>
> target = expr1 ?? expr2 ?? expr3
>
> You'd instead write None-coalescing as:
>
> target = exists(expr1) ?? exists(expr2) ?? expr3
>
> and None-propagating as:
>
> target = missing(expr1) ?? missing(expr2) ?? expr3
>
> with ?? being a protocol-driven short-circuiting binary operator
> controlled by the left operand rather than defining any particular
> semantics of its own.
I am sorry that I had to read this twice to get what you mean.
>
> The "obj?." and "obj?[]" would then be shorthand for particular uses
> of "missing(obj) ?? ..." that avoid duplicate evaluation of the left
> operand (as well as bypassing the overhead of actually creating a
> "missing" instance).
That could work if we accept that ?. and ?[] is only about the left
hand-side. However, as the ? visually applies also to the
attribute/index access on the right, which means it could be a more
readable way of doing
getattr(x, 'attr', None)
or
x[0] if len(x) > 0 else None
Imagine you need to work with incomplete data and do some chaining with
the new syntax. As soon as one single attribute isn't there, we hit an
exception. The same for index.
If the ?. and ?[] are introduced, I think applying the "non-existence"
property also the right hand make sense here as well for a wide range of
applications.
Best,
Sven
More information about the Python-ideas
mailing list