Sub topic 1
Where attributes live by default: the instance __dict__
When you write self.x = 1 in a method, Python has to put the value 1 somewhere and remember that it belongs to the name x on that one object. In an ordinary class, that place is a dictionary attached to the instance. This chapter explains how that dictionary works and how it interacts with class attributes and descriptors. It also covers the costs of the design. The later chapters on __slots__ only make sense once you know what they replace.
Prerequisites
This chapter assumes you can already do the following:
- Define a class with
__init__and assign instance attributes withself.name = value. - Tell instance attributes (set per object) from class attributes (set once on the class body).
- Read a basic inheritance hierarchy, where a subclass names a parent in parentheses.
- Use dictionaries: create them, read and set keys, delete keys, and iterate over them.
You don't need to know anything about descriptors or __slots__. The chapter introduces the little you need about descriptors.
The instance __dict__
Most Python objects you create from your own classes carry a dictionary that holds their attributes. It is available as __dict__:
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 output is:
{'x': 1, 'y': 2}
{'x': 1, 'y': 2, 'z': 3}Each key is the attribute name as a string, and each value is whatever you assigned. The statement p.z = 3 did not need z to be declared anywhere. Python simply added a key to the dictionary. This is the core of the default model: an instance is a thin object with a pointer to a dict, and attribute assignment is dict assignment.
Each instance has its own dictionary, so changes to one object never show up in another:
class Box:
pass
a = Box()
b = Box()
a.label = "first"
print(a.__dict__)
print(b.__dict__)
print(a.__dict__ is b.__dict__)This prints {'label': 'first'}, then {}, then False.
Reading and writing through the dict
The usual attribute syntax and the dictionary are two views of the same storage. The following program uses several of them:
class Config:
pass
c = Config()
c.__dict__["debug"] = True
print(c.debug)
setattr(c, "level", 3)
print(vars(c))
del c.debug
print(vars(c))
print(getattr(c, "missing", "default"))The output is:
True
{'debug': True, 'level': 3}
{'level': 3}
defaultA few points follow from this:
- Writing a key into
__dict__makes an attribute appear. Python does not check anything else. vars(obj)returnsobj.__dict__. It is the idiomatic way to read it.setattr,getattr, anddelattrtake the name as a string. They work on the dict like the dotted syntax does, and are handy when names come from data such as a config file.del c.debugremoves the key.
The dict is a plain dict, so ordinary dict tools work on it. Insertion order is preserved, which is why vars(p) lists x, y, z in the order you assigned them. Copying an object's state can be as simple as dict(vars(p)).
Attribute assignment is open-ended
Because assignment only adds keys, the dict-based model allows several things that people sometimes do by accident:
- Typos create new attributes silently.
p.xx = 5does not raise an error. It adds a new keyxx. - Two instances of one class can have different attribute sets.
- Attributes can be added or removed after
__init__has finished.
This flexibility is useful for prototypes, for objects built from loaded data, and for tools that attach extra information to objects. It is also the main thing __slots__ takes away, as later chapters show.
How a lookup finds an attribute
Writing a value is easy. Reading obj.name is more subtle, because Python checks more than the instance dict. The details matter whenever a class and its instances use the same name.
The rule for a normal read, simplified, is:
- Search the class (and its parents, in method resolution order) for
name. - If you find a data descriptor there, call it and use its result. A data descriptor is a class attribute whose type defines both a getter and a setter or deleter. A
propertyis the common example. - Otherwise, if
nameis a key in the instance's__dict__, return that value. - Otherwise, if the class search found something, use it. A plain value is returned as is, and a function becomes a bound method (functions are non-data descriptors, which have a getter only).
- Otherwise, raise
AttributeError.
The order has visible consequences. A property wins over a same-named key in the instance dict:
class Temp:
@property
def celsius(self):
return 20
t = Temp()
t.__dict__["celsius"] = 99
print(t.celsius)This prints 20. The dict entry exists, but the data descriptor is checked first.
A plain method loses to the instance dict:
class Greeter:
def hello(self):
return "class"
g = Greeter()
g.__dict__["hello"] = lambda: "instance"
print(g.hello())This prints instance. A function is a non-data descriptor, so the instance dict takes precedence.
Class attributes and shadowing
The same ordering explains how a class attribute and an instance attribute interact. Assignment through an instance always writes to the instance dict. It never changes the class:
class Counter:
step = 1
def __init__(self):
self.count = 0
a = Counter()
b = Counter()
a.step = 10
print(a.step, b.step, Counter.step)
print(a.__dict__)
print(b.__dict__)
del a.step
print(a.step)The output is:
10 1 1
{'count': 0, 'step': 10}
{'count': 0}
1a.step = 10 created a key in a's dict, which shadows the class value for a only. Deleting that key makes the class value visible again. Instance b never had the key, so it kept reading Counter.step. This pattern, a class attribute used as a default that an instance can override, is common in dict-based classes. Remember it, because the chapter on defaults and class-variable conflicts shows that __slots__ handles it differently.
What the class dict is, and is not
Classes have a __dict__ too, but it is not the same kind of object:
class Counter:
step = 1
print(type(Counter.__dict__).__name__)
try:
Counter.__dict__["step"] = 5
except TypeError as exc:
print("TypeError:", exc)
Counter.step = 5
print(Counter.step)The output is:
mappingproxy
TypeError: 'mappingproxy' object does not support item assignment
5A class's __dict__ is a read-only view. You change class attributes with normal assignment (Counter.step = 5), not by writing into the dict. Instance dicts have no such protection, so writing to them directly works.
The class dict also holds things that instances do not, such as methods and descriptors. Compare what each level holds:
| Where | Typical contents | Writable through `__dict__` |
|---|---|---|
| `obj.__dict__` | The per-object attribute values | Yes |
| `type(obj).__dict__` | Methods, class variables, descriptors | No (read-only view) |
| `type(obj).__mro__` parents | Inherited methods and class variables | No |
Objects that have no __dict__
Not every object stores attributes this way. Many built-in types have no instance dict:
for obj in (1, "text", [1, 2], object()):
print(type(obj).__name__, hasattr(obj, "__dict__"))
try:
object().x = 1
except AttributeError as exc:
print("AttributeError:", exc)
try:
vars(1)
except TypeError as exc:
print("TypeError:", exc)The output is:
int False
str False
list False
object False
AttributeError: 'object' object has no attribute 'x'
TypeError: vars() argument must have __dict__ attributeTwo details are worth noting. First, a bare object() instance has no dict, so you cannot attach attributes to it. A class you write with an empty body (class Box: pass) does get one, because Python adds the dict slot unless told otherwise. Second, vars() fails on objects without a dict. It raises TypeError, not AttributeError.
This shows that "attributes live in __dict__" is a default for user-defined classes, not a universal law. The next chapter shows how you can opt out of it for your own classes.
The cost of a dict per instance
The flexibility comes with a memory price. A dict is a general hash table, so even a small one reserves space for a hash index, entries, and bookkeeping. If your program creates millions of small objects, each with a dict, those overheads add up.
CPython reduces the cost with a few optimizations:
- Key-sharing dictionaries (since Python 3.3). Instances of the same class tend to use the same attribute names in the same order. CPython stores the names once, in a table shared by the class, and each instance keeps only its values.
- Lazy dict creation (in recent versions). In newer CPython releases, an instance can store its values directly inside the object. The real
dictobject is built only if something asks for__dict__.
You should treat these as implementation details. They differ between Python versions and between implementations such as PyPy, and you should not rely on them in code. What they mean in practice is that the memory cost of a dict per instance is smaller than a naive estimate suggests, and it has shrunk over time. The chapter on measuring memory shows how to compare sizes without overstating the difference.
Common errors
- Assuming a typo raises an error. With a dict,
p.colour = "red"adds a new attribute, even if you meantp.color. The mistake shows up later, as a wrong value or anAttributeErroron read. - Mutating a class attribute through an instance.
a.items.append(1)changes the list shared by every instance ifitemsis a class-level list, because no assignment happens and no instance key is created. Onlya.items = [...]creates an instance attribute. - Writing into
Class.__dict__. It raisesTypeError. Usesetattr(Class, name, value)or assignment. - Expecting a property to be overridden by
__dict__. Data descriptors win, as theTempexample showed. - Calling
vars()on a built-in value. It raisesTypeErrorfor types with no dict.
Summary
- A regular instance of a user-defined class keeps its attributes in a per-instance dict, available as
obj.__dict__orvars(obj). - Assigning, deleting,
setattr, anddelattroperate on that dict, so attributes can be added or removed freely. - Reads check data descriptors on the class first, then the instance dict, then the class.
- Instance assignment shadows class attributes and never modifies the class.
- Many built-in types have no dict, and CPython stores dicts compactly where it can.
- The open-ended dict is the source of both the flexibility and the memory cost that
__slots__addresses.
Exercise
Given the class below, predict the output of the three print calls, and explain why. class Widget: size = 5 w = Widget() w.size = 8 print(w.size, Widget.size) print(vars(w)) del w.size print(w.size)
Show answer
The first print shows 8 5, because w.size = 8 creates an instance key that shadows the class attribute while Widget.size stays 5. The second print shows {'size': 8}, the instance dict. After del w.size removes the instance key, the lookup falls back to the class, so the third print shows 5.
Exercise
A class defines @property def total(self). You run obj.__dict__["total"] = 100 and then read obj.total. Which value do you get, and which rule of attribute lookup explains it? Would the answer change if total were a regular method instead of a property?
Show answer
You get the value returned by the property getter, not 100. A property is a data descriptor, and data descriptors on the class are checked before the instance dict. If total were a regular method, it would be a non-data descriptor. The instance dict would then take precedence, and obj.total would return 100.
Exercise
Why does object().x = 1 raise AttributeError while the same assignment works on an instance of class Box: pass?
Show answer
A bare object() instance has no __dict__, so there is nowhere to store a new attribute. A user-defined class gets an instance __dict__ by default, even with an empty body, so the assignment adds a key to it.