[Python-ideas] accurate errors for "magic" methods
Steven D'Aprano
steve at pearwood.info
Fri Apr 10 06:45:12 CEST 2009
On Fri, 10 Apr 2009 03:56:16 am Georg Brandl wrote:
> spir schrieb:
> > Actually, I'm wrong: it's perfectly clear as long as the programmer
> > is able to follow all the necessary reflexion path; then probably
> > also able to solve the problem without any help from python.
> >
> > The issue here is that a very specific (and meaningful) case
> > (dict-like behaviour missing) is adressed using a very generic (and
> > thus helpless) message (attributeError).
> >
> > I think error cases about "magic" methods, that implement
> > conceptually meaningful behaviours, should have appropriate
> > messages. In the case above, maybe something like: "Values instance
> > is not an item container (no __getitem__ method found)."
>
> The time machine strikes again:
> >>> class A(object): pass
>
> ...
>
> >>> A()['a']
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'A' object is unsubscriptable
>
>
> (the difference being that A is new-style, while Values is
> old-style.)
Except that the error "object is unsubscriptable" might as well be in
Klingon to most people, particularly newbies.
(1) It's easy to misread it as "unscriptable", which is even more
mysterious.
(2) As far as I know, there's no tradition of describing key or index
lookup as "subscripting" in Python. I've never noticed it in doc
strings or the online docs, and after hanging around comp.lang.python
extensively for years, I feel safe to say it's not a common term among
even experienced Python developers. I suppose that there's a weak
connection between index lookup and subscripts in mathematics.
(3) The classic error message tells the newbie exactly what the error
is: the object has no __getitem__ method. The new error message tells
the newbie nothing useful. Given that obj is unsubscriptable, what
needs to be done to make it subscriptable?
--
Steven D'Aprano
More information about the Python-ideas
mailing list