[Python-ideas] PEP 505: None-aware operators: operators ?= and ?? and OR

MRAB python at mrabarnett.plus.com
Thu Jul 19 15:41:41 EDT 2018


On 2018-07-19 20:23, Terry Reedy wrote:
> On 7/19/2018 8:30 AM, Jonathan Fine wrote:
>> Hi
>> 
>>> There is a formatted version of this PEP at
>>> https://www.python.org/dev/peps/pep-0505/
>> 
>> I've taken a look at this, and have some comments on the first two
>> examples drawn from standard library code. (And a very grateful +10
>> for writing a script to find such examples.)
>> 
>> I've started a subthread, just to discuss the ?= and ?? operators. And
>> something newish, that I call OR.
>> 
>> FIRST EXAMPLE
>> The first example is
>> ---
>>  From bisect.py:
>> def insort_right(a, x, lo=0, hi=None):
>>      # ...
>>      if hi is None:
>>          hi = len(a)
>> ---
>> 
>> Here, None is a sentinel value. The simpler code
>> ---
>>    hi = hi or len(a)
>> ---
>> fails when hi is zero (or any other value that is False in the boolean context).
>> 
>> This can be fixed by introducing a new operator OR which is similar to
>> 'or' but has the semantics this example requires. Thus, given OR we
>> can write
>> ---
>>    hi = hi OR len(a)
> 
> Antoine Pitrou proposed the same thing, using the existing 'else' as the
> spelling.  'hi else len(s)' abbreviates the existing
> 'hi if hi is not None else len(s)'.
> with the boilerplate 'if x is not None' removed.
> 
>> ---
>> where (A OR B) returns A if A is not None, otherwise it returns B.
>> 
>> (Recall that (A or B) returns A if bool(A), otherwise it returns B.)
> 
> To make the parallel more obvious, (A or B) also abbreviates
> tem = A; tem if bool(tem) is not False else B
> 
If you want a not-too-long keyword, how about "anders"? :-)


More information about the Python-ideas mailing list