On Oct 22, 2019, at 11:39, Mike Miller <python-id...@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.

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/5N67XBNGAEQK2OF3XALT4TPUTMLJYNUF/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to