[Python-ideas] accurate errors for "magic" methods

spir denis.spir at free.fr
Thu Apr 9 19:08:36 CEST 2009


Below a post on python-tutor and my trial to explain what happens.

> The error I get when running the above code:
> Traceback (most recent call last):
>   File "listinclass.py", line 34, in <module>
>     test.load_ini()
>   File "listinclass.py", line 17, in load_ini
>     print self.opt['inifile']
> AttributeError: Values instance has no attribute '__getitem__'

This means the following:
* You're trying to access an item inside something called self.opt, by using a key: 'inifile'.
* self.opt should then be a kind of container able to return you an item from a key; in other words, it is supposed to be an object that behaves like a dictionary, right?
* The "magic" method the allows this behaviour is called __getitem__ (the same as for list indexing, actually). So that python looks for this method attribute in the class of self.opt, that happens to be Values, and tells you...

Sure, not very clear!

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)."

There may be a sensible relationship with the ABC hierarchy that precisely provides naming and specification to types implementating (some of) the magic methods.
I would love a BehaviourError ;-)

la vita e estrany

More information about the Python-ideas mailing list