
On Tue, Oct 22, 2019 at 11:39:59AM -0700, Mike Miller wrote:
On 2019-10-18 10:23, Ricky Teachey wrote:
but i'm -0 because i am very concerned it will not be obvious to new learners, without constantly looking it up, whether adding two mappings together would either:
The big trade off I'm gathering from this mega-thread is that the |, |= operators are more accurate, but less obvious to newcomers, who will first try +, += instead.
I'm surprised by that description. I don't think it is just newcomers who either suggest or prefer plus over pipe, and I don't think that pipe is "more accurate". As I pointed out in the PEP, plus often gets used for non-commutative operations (such as concatenation and ordinal arithmetic) but I am unaware of the union operator ∪ or | as spelled in Python ever being used for a non-commutative operation. Contrary to the views of many people upset that dict + would be non- commutative, it is arguably *more natural* to use plus for a non- commutative operation than it would be to use pipe. The biggest advantage of pipe is that it naturally lends itself to the rest of the set operations. But using pipe for a non-commutative operator is far less common than using plus.
I've tried them in this order myself several times over the years.
Had an idea, why not choose the more accurate syntax: |, |= after all? Then, to help newcomers and forgetful pros a custom error message is implemented for +, +=. In pseudo C/Python, something like this:
class dict:
def __add__(self, other):
if isinstance(other, dict): raise TypeError( 'unsupported operand type(s) for +: … ' 'Dictionary merging leads to last-value-wins data ' 'loss. If acceptable, use the union "|" operator.' )
I think that is patronising to anyone, newbies and experienced programmers alike, who know and expect that merging dicts with an operator will have the same semantics as merging them with the update method.
I think it is worth it to lead the newcomer to a moment's reflection on why dictionary combining/merging is potentially lossy.
Should we also force newcomers to give a moment's reflection on why item assignment ``mydict[key] = value`` is potentially "lossy"? How about ``mystring.replace(old, new)`` or opening a file for writing? I think that we should trust that when the programmer asks to update a dict with new values (either in-place or as a copy), it is because they don't want the old values any more. Even if they don't know what they are doing, it is not the place of the interpreter to treat them as an ignoramus that needs to be forced into reflecting on the consequences of their action, as if they were a naughty little schoolboy being told off by their headmaster. -- Steven