RE none-aware operators in general:
+1 overall for the latest version of PEP 505 and the utility of ?? in
particular. There are several places in my code that could be simplified
with ??.
find-pep505.py on my current Django-oriented codebase gives:
Total None-coalescing `if` blocks: 43
Total [possible] None-coalescing `or`: 4
Total None-coalescing ternaries: 8
Total Safe navigation `and`: 0
Total Safe navigation `if` blocks: 6
Total Safe navigation ternaries: 17
RE OR and ||:
* -1 for "OR" as an operator. Insufficiently distinct from "or". Reads
the same out loud despite being a different operator.
* -1 for "||" with none-aware semantics. This differs from the semantics
in every C-derived language I can think of, which will be confusing to
several other developers.
David Foster | Seattle, WA, USA
On 7/19/18 5: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)
---
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?
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/