0

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).

6
  • Short lazy answer: __slots__; also dict is implemented in C, and you're inheriting it. Commented Jan 12, 2012 at 22:21
  • 3
    what python version are you using? b.p = 1 works both in 2.7.2 and 3.2 Commented Jan 12, 2012 at 22:24
  • Terribly sorry, it does work for b. Updated question to reflect this. Commented Jan 12, 2012 at 22:38
  • You can make chnages to the built-in classes thenselves- you have to create subclasses of them. Commented Jan 12, 2012 at 23:41
  • 2
    @BasicWolf: Why do you say that? Commented Jan 13, 2012 at 14:04

2 Answers 2

4

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 list and dict to 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.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to subclass dict you can always use UserDict (here the documentation).

And it works with what you're trying to do:

from collections import UserDict

a = UserDict()
a.p = 10 # works fine

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.