Python raises TypeError when NotImplemented is returned from __add__,
__invert__ etc. and __radd__ etc. aren't available.
However, this disallows the customization of error messages. For example, in
Python 3.8, __float__ etc. were removed from complex to allow methods like
__rfloat__. But this makes abs(z) undiscoverable for many users. The original
error message is very helpful.
I suggest to make a way for this usage. Maybe NotImplementedType can accept
*args, and NotImplemented can be callable, equal to __init__:
>>> class A:
def __add__(self, other):
return NotImplemented # Just like before
def __neg__(self, other):
return NotImplemented(f'bad operand type for unary -:
{type(self).__name__!r}; use ~ to invert') # <--
def __invert__(self):
return ~5
>>> a = A()
>>> a + 2
TypeError: unsupported operand type(s) for +: 'A' and 'int'
>>> -a
TypeError: bad operand type for unary -: 'A'; use ~ to invert
>>> ~a
-6
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/6GX5XJCSVR3SKSZE342KIASIWJDUZGVN/
Code of Conduct: http://python.org/psf/codeofconduct/