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

Jonathan Fine jfine2358 at gmail.com
Thu Jul 19 08:30:33 EDT 2018


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)
---
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.)

SECOND EXAMPLE
The second example is
---
>From calendar.py:
encoding = options.encoding
if encoding is None:
    encoding = sys.getdefaultencoding()
optdict = dict(encoding=encoding, css=options.css)
---

Once we have OR we would write this as
---
encoding = encoding OR sys.getdefaultencoding()
optdict = dict(encoding=encoding, css=options.css)
---

And from here we can condense into a single (longish) line:
---
optdict = dict(encoding=encoding OR sys.getdefaultencoding(), css=options.css)
--

SUMMARY
Here, for reference, are the suggestions using ?= and ?? in PEP 505.
---
hi ??= len(a)
---
optdict = dict(encoding=encoding ?? sys.getdefaultencoding(), css=options.css)
---

Comments ?? suggestions. For example, would a None-aware AND operator be useful?

-- 
Jonathan


More information about the Python-ideas mailing list