Fabian
Fabian

Reputation: 4348

If you subclass from dict, why is __dict__ always empty?

I have a question regarding the subclassing behaviour in Python 2.7.

If I subclass from the built-in dict type, it seems that __ dict __ is always empty. Where does Python save the key/value pairs?

>>> class Foobar(dict):
...     pass
... 
>>> foobar = Foobar()
>>> foobar.__dict__
{}
>>> foobar['test'] = 1
>>> foobar.__dict__
{}
>>> 

Upvotes: 3

Views: 1549

Answers (5)

senderle
senderle

Reputation: 150987

A partial answer is that you're misunderstanding the purpose of __dict__. __dict__ is used to store attributes, not items, and it's present in most user-defined objects. Indeed, if you subclass dict in the appropriate way, __dict__ will have values in it.

>>> class Foo(dict):
...     def __init__(self, *args, **kwargs):
...         super(Foo, self).__init__(*args, **kwargs)
...         self.banana = 'banana'
...         self['banana'] = 'not really a banana'
... 
>>> f = Foo()
>>> f.__dict__
{'banana': 'banana'}
>>> f.banana
'banana'
>>> f['banana']
'not really a banana'

Upvotes: 5

Kabie
Kabie

Reputation: 10673

__dict__ is for attributes:

>>> class D(dict):
    pass

>>> d=D()
>>> d.__dict__
{}
>>> d.x=5
>>> d.__dict__
{'x': 5}

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375574

__dict__ is where an object's attributes are stored. Dicts' items are not attributes, they are items. Most dicts have no data attributes.

BTW: subclassing dict is difficult to do properly, depending what you are trying to achieve. For example, you can override its __setitem__ method, but then update won't use it.

Upvotes: 6

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Because a dict object doesn't actually have __dict__ so the __dict__ you are referencing is the dict local to your object Foobar. Because Foobar has no attributes __dict__ is empty.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612904

The dict class is implemented purely in C as a built-in. Its data storage is private to that implementation.

As a thought experiment, imagine if it put the name/value pairs into a Python dict, how would that dict store them? In another Python dict? And then, well, you get the idea!

Upvotes: 5

Related Questions