[Python-Dev] Exception for setting attributes of built-in type

Nick Coghlan ncoghlan at gmail.com
Mon Jun 15 23:31:06 CEST 2009

Benjamin Peterson wrote:
> 2009/6/15 Nick Coghlan <ncoghlan at gmail.com>:
>> Guido van Rossum wrote:
>>> In general, CPython isn't always consistent in raising AttributeError
>>> and TypeError when it comes to such policy issues: there are various
>>> places that raise TypeError in typeobject.c (and probably elsewhere)
>>> that simply forbid setting a specific attribute (another example is
>>> __name__).
>> We're pretty inconsistent when it comes to looking up special methods as
>> well - those that are looked up through dedicated slots in abstract.c
>> usually raise TypeError, while those that are looked up via a PyType
>> method usually raise AttributeError.
> What's a PyType method?

I was misremembering - for some reason I thought:
a) _PyObject_LookupSpecial was a PyType method
b) That it raised AttributeError itself instead of letting the caller
decide what error to raise

It's still the case that (e.g.) special_lookup() in ceval.c raises an
AttributeError, as do special method lookups from Python of the form

Whether CPython raises TypeError or AttributeError when it comes to
special methods is really pretty arbitrary rather than a matter of any
grand design.


P.S. If anyone feels like digging into the archives, the last time I can
recall this topic coming up is when I was concerned about the original
with statement implementation raising AttributeError rather than
TypeError when it couldn't find an __enter__ or __exit__ method. Guido
chimed in then (as now) to say that either exception was fine.

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list