Sean Pianka Sean Pianka - 10 months ago 41
Python Question

Why are instances of the `object` class immutable in Python?

>>> a = object()
>>> a.x = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'x'
>>> b = lambda:0
>>> b.x = 5
>>> b.x

Why do instances of the
class not have a
, causing it to behave as semantically immutable? What were the reasons for choosing this design?

Specifically, why:

instances of types defined in C don't have a __dict__ attribute by

As noted in this question.

Answer Source

The documentation for Python 2 is not very helpful in giving an explanation as to why you cannot assign attributes to an object(), but the documentation for Python 3 provides a bit more information:

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

Thus, the reason you cannot add arbitrary attributes to your object() appears to be because of the fact that object() instances do not have an implementation of the __dict__ method, no because object() instances are immutable.

Another interesting thing, but perhaps not relevant to the discussion at hand, is that while an instance of object may not have a __dict__ implementation, the object class itself does:

>>> hasattr(object, '__dict__')

As for why this is, I cannot find any exact for reasons for why object() doesn't have a __dict__. Is is probably because - as @tdelany has already hit on in the comments - it is an implementation detail. If you really want a definitive answer, you should ask Guido himself.