Sub topic 1
Where attributes live by default: the instance __dict__
Prerequisites
This chapter assumes you can do the following:
- Define a class with
__init__in Python. - Tell instance attributes from class attributes.
- Read basic inheritance code.
- Use dictionaries: keys, values, and item assignment.
The examples run on any recent CPython 3 release.
Every instance carries a dictionary
When you write self.x = x inside __init__, Python has to put the value somewhere. By default it stores the value in a dictionary attached to that one instance. That dictionary is called __dict__. It maps attribute names (as strings) to their values.
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
p = PlainPoint(1, 2)
print(p.__dict__)
p.z = 3
print(p.__dict__)The first print shows {'x': 1, 'y': 2}. After p.z = 3, the second shows {'x': 1, 'y': 2, 'z': 3}. Nothing in the class mentioned z. The assignment simply added a new key to the instance's dictionary.
This is the default storage model. Each instance has its own __dict__, so two instances of the same class can hold different sets of attributes.
How attribute lookup uses the dictionary
Reading p.x is not a plain dictionary read. Python looks in several places, in this general order:
- The class (and its parents) for a data descriptor named
x. A data descriptor is an object that defines__set__or__delete__, such as a property. - The instance
__dict__. - The class (and its parents) for a non-data descriptor or a plain class attribute. Functions defined with
defare non-data descriptors, which is how methods are found.
This order explains a common surprise. An instance attribute shadows a class attribute of the same name, but a property on the class wins over the instance dictionary.
class Counter:
step = 1
c = Counter()
print(c.step)
c.step = 10
print(c.step)
print(Counter.step)
print(c.__dict__)This prints 1, 10, 1, and {'step': 10}. The assignment c.step = 10 wrote into the instance dictionary. It did not change the class attribute. The class still reports 1.
Because it is a dictionary, you can use it like one
The instance dictionary is an ordinary dict, so you can read it and change it directly.
class Config:
pass
cfg = Config()
cfg.__dict__["debug"] = True
print(cfg.debug)
for name, value in vars(cfg).items():
print(name, value)vars(obj) returns obj.__dict__, and it is the usual way to read it. Writing to the dictionary directly bypasses descriptors. If the class defined a property named debug, the property would still take priority when you read cfg.debug, so the dictionary entry would be ignored.
Many tools rely on this model. Debuggers print __dict__ to show an object's state. Serialization helpers often copy it. Frameworks add attributes at runtime. All of that works because attribute storage is open-ended.
The cost of flexibility
A dictionary can grow, shrink, and hold any names. That flexibility has two costs.
- Memory. Every instance owns a separate dictionary object. A dictionary stores a hash table, and that table takes space even when it holds only two entries. With many small instances, the dictionaries can take more memory than the values themselves.
- No fixed shape. Any code holding a reference can add attributes. A typo such as
p.xx = 5creates a new attribute silently instead of raising an error.
p = PlainPoint(1, 2)
p.xx = 5
print(p.x)
print(p.__dict__)The value of p.x is still 1, and xx now sits next to the real attributes. Nothing warned you.
CPython has optimizations that reduce the memory cost of instance dictionaries, such as sharing key tables between instances of one class. Exact savings depend on the Python version, so a later chapter measures them rather than assuming a number.
What comes next
__slots__ is a class-level declaration that replaces the per-instance dictionary with fixed storage. The next chapter shows the syntax and what changes. Keep this chapter's picture in mind: a dictionary per instance, open to any new name.
Exercise
Given class A: n = 1 and a = A(), what do a.n, A.n, and a.__dict__ show after you run a.n = 2?
Show answer
a.n is 2 and A.n is still 1. a.__dict__ is {'n': 2}. The assignment created an instance attribute in the instance dictionary, which shadows the class attribute without changing it.
Exercise
A class defines @property def size(self) with a setter. You run obj.__dict__["size"] = 99 and then read obj.size. Which value do you get, and why?
Show answer
You get the value from the property, not 99. A property is a data descriptor, and data descriptors on the class take priority over the instance dictionary during lookup.