[Python-Dev] Exception for setting attributes of built-in type
Guido van Rossum
guido at python.org
Mon Jun 15 01:19:18 CEST 2009
On Sun, Jun 14, 2009 at 3:42 PM, MRAB<python at mrabarnett.plus.com> wrote:
> Seo Sanghyeon wrote:
>> Exception for setting attributes of built-in type differs between
>> CPython and IronPython. This is not purely theoretical, as
>> zope.interface tries to set Implements declaration as __implemented__
>> attribute of built-in type object, and excepts TypeError.
>> Python 2.6.1
>>>>> object.flag = True
>> TypeError: can't set attributes of built-in/extension type 'object'
>> IronPython 2.6
>>>>> object.flag = True
>> AttributeError: 'object' object has no attribute 'flag'
>> I was surprised that CPython raises TypeError. Library Reference seems
>> to mention it here:
>> exception AttributeError
>> Raised when an attribute reference or assignment fails. (When an
>> object does not support attribute references or attribute assignments
>> at all, TypeError is raised.)
>> What does it mean that "an object does not support attribute
>> references or attribute assignments at all"?
> Here's my guess:
> Some objects have a fixed (and possibly empty) set of attributes.
> Attempting to add a new attribute or get a non-existent attribute raises
> an AttributeError.
> Other objects, such as types (are there any that aren't types?), don't
> have attributes at all. Attempting to add or get an attribute raises a
This particular error comes (grep tells me :-) from type_setattro() in
Objects/typeobject.c. It makes a specific check whether the type
object whose attribute you want to set is a "built-in type" (this is
done by checking the HEAPTYPE flag, which is never set for built-in
types and always for user-defined types). For built-in types it
disallows setting attributes. This is a pure policy issue: it prevents
different 3rd party modules to make incompatible modifications of
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
Given how poorly Python exceptions are specified in general, I don't
want to hold IronPython to this standard (nor CPython :-). The reason
this breaks zope.interfaces in IronPython is probably just that
zope.interfaces was primarily written/tested against CPython.
Going back to the phrase quoted from the reference manual, it's
probably referring to the possibility that a type's tp_getattro slot
is NULL; but even so it's wrong: PyObject_GetAttr() raises
AttributeError in this case.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev