[Python-ideas] Fw: accurate errors for "magic" methods
Chris Rebert
pyideas at rebertia.com
Wed Apr 15 13:00:59 CEST 2009
> ================
> Use exception chaining and rephrase the error message to get something like:
>
> AttributeError: class 'A' has no attribute '__getitem__'
> The above exception was the direct cause of the following exception:
> TypeError: 'A' object does not support the 'get item' operator
> ================
>
> Much better, I guess. But actually such errors often happen on objects for which a 'get item' operation simply makes no sense (because of another design or programming error). A typical case beeing None itself (see what I mean?). The remedy is rarely to add a __getitem__ method to a custom container class. Rather it is to check whether a container was properly returned by a previous operation:
I don't think it really adds any confusion in the "you shouldn't have
tried subscripting this in the first place" case. The message seems
pretty clear: you can't subscript this thing; why?: it doesn't have a
__getitem__; why might that be?: it might not make sense to subscript
it.
If you get the error with None, it seems fairly clear that (A) you
can't modify NoneType (B) trying to subscript None makes no sense. In
any case, it seems a significant improvement over the current error
message to me.
> cont = ...
> try:
> result = cont[0]
> except AttributeError:
> raise ValueError("Cannot find...")
>
> As a consequence, I still think that mentioning the notion of container is helpful, eg:
> TypeError: 'A' object is not a container able to support the 'get item' operator.
See the quote from Guido earlier in the thread. Not everything
defining the operator is necessarily a container.
>
> Also, what do you think of "item extraction" as an understandable wording for "use of []" or "call to __getitem__"(*).
Sounds okay. I was thinking "item access" personally. Feel free to
suggest it on the bug page.
> AttributeError: class 'A' has no attribute '__getitem__'
> The above exception was the direct cause of the following exception:
> TypeError: 'A' object is not a container able to support item extraction.
>
> If ever such an idiom as "item extraction" is found correct, it could be reused in the ABC lexicon, for consistency.
Agreed. The x[y] operator needs a canonical name that makes sense for
common uses of the operator, and this name should be used consistently
throughout the docs.
> (*) An issue for finding a proper idiom is that getitem is also called for slicing. A single item is not a mini-slice.
Cheers,
Chris
--
I have a blog:
http://blog.rebertia.com
More information about the Python-ideas
mailing list