Why doesn’t it work for the built-in classes?
Is using a subclass the best approach to fix it, or will I run into some hidden problems?
a = {}
a.p = 1 # raises AttributeError
class B(dict):
pass
b = B()
b.p = 1 # works
EDIT: my original comment that it doesn’t work for b was incorrect (I made a mistake).
The builtin classes do not have the ability to have arbitrary attributes. This is done for reasons of performance, especially memory usage, you want the built-in classes like
listanddictto be as small as possible so you can have many of them.Therefore the built-in classes do not have the
__dict__dictionary that is needed for arbitrary attributes to work.You can achieve the same for your classes. If they are written in C you simply do not implement the
__dict__support. If they are written in Python you use slots.