
On Oct 22, 2019, at 11:39, Mike Miller <python-ideas@mgmiller.net> wrote:
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.' ) else: raise TypeError(std_err_msg)
This seems nifty—but will it break the __radd__ protocol? In other words: class FancyDict(dict): def __add__(self, other): # handles other being a plain dict just fine def __radd__(self, other): # handles other being a plain dict just fine … you want to make sure that adding a dict (or other dict subclass) and a FancyDict in either order calls the FancyDict method. Off the top of my head, I think it’s safe—and if not it would be safe to move your logic to dict.__radd__ and have __add__ either not there or return NotImplemented, because there’s a rule that if one object is an instance of a subclass of the other object’s type it gets first dibs. But someone needs to read the data model docs carefully—and also check what happens if both types are C extensions (since dict is). Anyway, while I don’t know if there is precedent for anything like this in a builtin type’s methods, there is precedent in builtin functions, like sum, so I think if it’s doable it might be acceptable. The only question is whether you’d want the same error for adding instances of subclasses of dict that don’t override the method(s)—and I think the answer there is yes, you would.