Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
5

Why do instances of the object class not have a __dict__, 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 default.

As noted in this question.

like image 303
Sean Pianka Avatar asked Nov 28 '16 21:11

Sean Pianka


1 Answers

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__ attribute, not because object() instances are immutable:

>>> hasattr(object(), '__dict__')
False
>>>

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__')
True

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

like image 181
Christian Dean Avatar answered Sep 22 '22 09:09

Christian Dean