[Python-ideas] Null coalescing operator

Guido van Rossum guido at python.org
Sat Sep 10 16:56:39 EDT 2016


On Sat, Sep 10, 2016 at 11:09 AM, MRAB <python at mrabarnett.plus.com> wrote:
> On 2016-09-10 18:44, Paul Moore wrote:
>>
>> On 10 September 2016 at 18:26, Guido van Rossum <guido at python.org> wrote:
>>>
>>> IMO the key syntax is
>>> simply one for accessing attributes returning None instead of raising
>>> AttributeError, so that e.g. `foo?.bar?.baz` is roughly equivalent to
>>> `foo.bar.baz if (foo is not None and foo.bar is not None) else None`,
>>> except evaluating foo and foo.bar only once.
>>
>>
>> If we're not looking to use all the other null-coalescing variants
>> (?=, ?(), ...) - which is something I'm pleased about, as I do think
>> that scattering that many ?'s about is likely to lead to ugly code -
>> then it would probably be fine to just use ? for this operation, so
>> we'd have foo?bar?baz rather than needing foo?.bar?.baz.
>>
> I think that's not as clear; the "?." at least looks like a form of
> attribute access.
>
> It would also mean that it would be more difficult to add the other
> null-coalescing variants later, if the need arose.

Indeed. And ?. is how this is spelled in some other lanuages (C# and Dart).

I forgot one detail that's in PEP 505: e.g. `foo?.bar.baz()` should be
implemented as `foo.bar.baz() if foo is not None else None`. IOW if
foo is None, the entire trailing section `.bar.baz()` should be
skipped. (But this is a property of `?.` as an alternative attribute
access operator; it doesn't mean `?` is a postfix operator on `foo`.)

Another issue already discussed in PEP 505 is a conflict with IPython
(Jupyter Notebook), which uses ? and ?? as custom syntax to request
help. But maybe it can be taught to only recognize those when they're
the last character(s) on the line?

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list