[Python-ideas] Null coalescing operator
Nick Coghlan
ncoghlan at gmail.com
Wed Nov 2 12:17:14 EDT 2016
On 3 November 2016 at 01:46, Guido van Rossum <guido at python.org> wrote:
> But I also recall learning CoffeeScript via cargo-culting a large existing
> codebase and having not the foggiest ideas when it made sense to use ?. and
> when plain . was enough. So I think this feature is not very
> new-user-friendly and I still expect that in the end we'll have two rejected
> PEPs. But first we need to agree on what even the right definition of ?. is.
> It's been frighteningly difficult to explain this even on this list, even
> though I have a very clear view in my head, and PEP 505 also has the same
> semantics and explains well why those are the right semantics. So that's
> another point against this. It's syntactic sugar causing lots of cavities.
Yeah, and so far the protocol based alternative I'm working on hasn't
been any less headache-inducing (Mark has been reviewing some early
iterations and had to draw a diagram to try to follow the proposed
control flow).
I think I have a way to simplify that idea further though, and if that
works out I should have something I'm willing to share with a wider
audience.
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.
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).
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list