24

I'm trying to understand the following snippet of code:

class Config(dict):
    def __init__(self):
        self.__dict__ = self

What is the purpose of the line self.__dict__ = self? I suppose it overrides the default __dict__ function with something that simply returns the object itself, but since Config inherits from dict I haven't been able to find any difference with the default behavior.

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

2 Answers2

17

Assigning the dictionary self to __dict__ allows attribute access and item access:

>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • 1
    I also tested that this behavior requires the `self.__dict__ = self` line in the `__init__` (if `Config` is derived from `dict` only, I get a `NameError` trying to call `c['abc']`). – Kurt Peek Oct 03 '16 at 13:43
  • 2
    Assigning to `__dict__` is always a bad idea. Please don't. You can implement the actually desired behavior via `__setattr__` without all the other side effects. – gps Mar 28 '19 at 17:57
  • @gps actually it's the opposite, I've tried a million ways to implement get/set attrib methods and always ends up with infinite recursion – MathCrackExchange Jul 12 '23 at 23:45
12

As per Python Document, object.__dict__ is:

A dictionary or other mapping object used to store an object’s (writable) attributes.

Below is the sample example:

>>> class TestClass(object):
...     def __init__(self):
...         self.a = 5
...         self.b = 'xyz'
... 
>>> test = TestClass()
>>> test.__dict__
{'a': 5, 'b': 'xyz'}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126