[Python-Dev] Pre-PEP: Exception Reorganization for Python 3.0
Jack Diederich
jack at performancedrivers.com
Sat Jul 30 17:20:33 CEST 2005
On Sat, Jul 30, 2005 at 06:41:51PM +1000, Nick Coghlan wrote:
> Brett Cannon wrote:
> > Don't forget this is Python 3.0; if it makes more sense we can break code.
>
> Or if he can be persuaded that ControlFlowException should exist as a peer of
> Exception and CriticalException. . .
>
> >>> +-- TypeError
> >>> +-- AttributeError (subclassing new)
> >
> > It seems a decision needs to be made as to whether the lack of an
> > attribute is a failure of using the wrong type of object, just a
> > failure to find something in an object, or a failure to find a name in
> > a namespace. I lean towards the first one, you like the second, and
> > Guido seems to like the third. $20 says Guido's opinion in the end
> > will matter more than ours. =)
>
> I think this is a context thing - whether or not an AttributeError is a
> TypeError or LookupError depends on the situation.
>
> In ducktyping, attributes are used to determine if the object is of the
> correct type. In this case, an AttributeError indicates a TypeError.
+1
> However, it isn't that uncommon to use an instance's namespace like a
> dictionary to avoid typing lots of square brackets and quotes (e.g. many
> configuration handling modules work this way). In this case, an AttributeError
> indicates a LookupError.
I expect any square-brackets (foo['bar'] or foo[7]) to be a LookupError or
a subclass (KeyError, IndexError). If AttributeError subclassed LookupError
you would have to work around it in common code where you are accessing
an attribute and doing a [] lookup on the same line.
class Foo(object):
bar = {'k' : ['A', 'B', 'C']}
try:
print Foo.barrr['j'][7] # could raise AttributeError, IndexError, KeyError
except (KeyError, IndexError): pass
If the attribute isn't there I made a coding mistake, if the key/index isn't
there my data source doesn't include that item (not a mistake, it just isn't
there).
> I think it's similar to the common need to convert from KeyError to
> AttributeError in __getattr__ methods - the extra attributes are looked up in
> some other container, and the resultant KeyError needs to be converted to an
> AttributeError by the __getattr__ method. That common use case still doesn't
> mean KeyError should subclass AttributeError.
The top level access should dictate which error it raises, even if attributes
are implemented with dictionaries. 'foo.bar' and 'foo.__dict__['bar']' look
different to me, even if the results on success are frequently the same.
Any chance str.index and list.index could raise IndexError instead of
ValueError in 3.0? Even after a few years of using them I still get this
wrong. index() isn't the same lookup as [], but my brain still slips and
expects a function named "index" to raise an "IndexError"
-jackdied
More information about the Python-Dev
mailing list