[Python-ideas] Null coalescing operators
Ron Adam
ron3200 at gmail.com
Tue Sep 22 04:18:33 CEST 2015
On 09/21/2015 03:44 PM, Terry Reedy wrote:
> On 9/21/2015 11:28 AM, Ron Adam wrote:
>
>> We could add a "not None" specific boolean operators just by appending !
>> to them.
>>
>> while! x: <--> while x != None:
>> if! x: <--> if x != None:
>>
>> a or! b <--> b if a != None else a
>> a and! b <--> a if a != None else b
>> not! x <--> x if x != None else None
>
> '!= None' should be 'is not None' in all examples.
Yes
> Since 'is not None'
> is a property of the object, so I think any abbreviation should be
> applied to the object, not the operator. "while x!", etcetera
My observation is that because None is the default return value from
functions (and methods), it is already a special case. While that isn't
directly related to None values in general, I think it does lend weight
to treating it specially.
Having None specific bool-type operators is both cleaner and more
efficient and avoids issues with false values. The byte code might look
like this...
>>> def value_or(x, y):
... return x or! y
...
>>> dis(value_or)
2 0 LOAD_FAST 0 (x)
3 JUMP_IF_NONE_OR_POP 9
6 LOAD_FAST 1 (y)
>> 9 RETURN_VALUE
It would not be sensitive to False values.
Applying the op to the object wouldn't quite work as expected.
What would x! return? True, or the object if not None?
And if it returns the object, what does this do when the value is 0 or
False, or an empty container.
result = x! or y # not the same as result = x or! y
The maybe(x) function would work the same as x! in this case.
I also think a trailing unary operator is kind of weird.
But I get the feeling from Guido response about over generalizations
that it may be too big of a change, and I agree it is a new concept I
haven't seen anywhere else. Maybe one to think about over time, and not
to rush into.
Cheers,
Ron
More information about the Python-ideas
mailing list