Error Messages for methods

In issue #130821 there was a proposal to unify error messages and @storchaka recommended opening a discuss here, so I’ll explain:
We decided to add a type before the method name so the messages will be updated anyway. And it would be convenient to make one template for such errors at the same time. There are several variants:
{TYPE}.__method__ should return ..., (...) (current state in parentheses)
{TYPE}.__method__ should return ..., not ... (or must return)

Here are some examples of such error messages:

__bool__ returned non-bool (type %T)
__index__ returned non-int (type %T)
__int__ returned non-int (type %T)
%.50s.__float__ returned non-float (type %.50s)
__buffer__ returned non-memoryview object
__annotate__ returned non-dict of type '%.100s'
__len__() should return >= 0
__hash__ method should return an integer
__init__() should return None, not '%.200s'
__sizeof__() should return >= 0
__getnewargs_ex__ should return a tuple, not '%.200s'
__getnewargs_ex__ should return a tuple of length 2, not %zd
__length_hint__() should return >= 0
__length_hint__ must be an integer, not %.100s
read() should return bytes
readall() should return bytes
decoder should return a string result, not '%.200s'
encoder should return a bytes object, not '%.200s'
iterator should return strings, not %.200s (the file should be opened in text mode)
1 Like

In RFC docs should means optional, must mean mandatory.

Changing the should’s to must’s could be considered at the same tine.

It is nice to see what was given, but sometimes there might not be a way to represent the state, or doing so can unnecessarily cause more errors.

For example, in those that should return >=0, it is clear that if the error is emitted, then what was given doesn’t satisfy that condition. If the return value were -2**9999999, it might not be nice nor useful to try to represent it.

This is the referenced GitHub issue: Inconsistent error messages when returning the wrong type for the type-conversion magic methods · Issue #130821 · python/cpython · GitHub