Sub topic 1
Where attributes live: instance and class `__dict__`
Before you can follow what obj.name does, you need to know where Python keeps the values that lookup searches. This chapter covers the two main places, the instance __dict__ and the class __dict__. It also covers what goes in each one and why writing behaves differently from reading. Later chapters build the full lookup procedure on this.
Prerequisites
This chapter assumes you can:
- Write classes with
__init__and methods, and create instances. - Tell an instance attribute (
self.x = ...) from a class attribute (assigned in the class body). - Read basic inheritance (
class B(A):). - Recognize special (dunder) methods such as
__init__and__repr__.
Attributes are stored in dictionaries
Most Python objects keep their attributes in a dictionary. For an instance, that dictionary is obj.__dict__. For a class, it is Cls.__dict__. Dotted access such as obj.name is mostly a search of these dictionaries, plus a few extra rules that later chapters cover.
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof"
d = Dog("Rex")
print(d.__dict__) # {'name': 'Rex'}
print("species" in d.__dict__) # False
print(d.species) # Canis familiaris
print(sorted(k for k in vars(Dog) if not k.startswith("__")))
# ['bark', 'species']The instance dictionary holds only what was assigned on that instance, here name. The class dictionary holds what was defined in the class body: species and the function bark. Reading d.species works even though species is not in d.__dict__, because the search continues to the class.
vars(obj) returns obj.__dict__. Prefer it to writing __dict__ directly in everyday code, since it reads more clearly and fails with a TypeError on objects that have no __dict__.
The instance dictionary
The instance dictionary is an ordinary dict. You can read it, add keys and remove keys, and the object's attributes change to match.
class Box:
pass
b = Box()
b.color = "red"
print(b.__dict__) # {'color': 'red'}
b.__dict__["size"] = 10 # same effect as b.size = 10
print(b.size) # 10
del b.color
print(b.__dict__) # {'size': 10}Two details matter for later chapters:
- Assignment
obj.x = valuenormally stores the value inobj.__dict__. It never writes to the class. (Descriptors can change this. That is the subject of this tutorial.) - Not every object has an instance dictionary. Instances of built-in types such as
inthave none, and classes that define__slots__do not get one by default.
try:
(1).__dict__
except AttributeError as e:
print(e) # 'int' object has no attribute '__dict__'The class dictionary
A class stores its own namespace in Cls.__dict__. This holds the methods, class attributes, and some bookkeeping entries Python adds, such as __module__ and __doc__.
Unlike an instance dictionary, Cls.__dict__ is not a plain dict. It is a read-only mappingproxy, a view that lets you inspect the namespace but not change it directly.
class Dog:
species = "Canis familiaris"
print(type(Dog.__dict__).__name__) # mappingproxy
try:
Dog.__dict__["species"] = "wolf"
except TypeError as e:
print(e) # 'mappingproxy' object does not support item assignment
Dog.species = "wolf" # the supported way
print(Dog.species) # wolfAssigning through the class (Dog.species = ..., or setattr(Dog, "species", ...)) goes through the class's own attribute machinery. This is how Python can keep internal caches consistent when a class changes. Writing into the dictionary directly would bypass that.
The class dictionary does not contain inherited names. vars(Dog) lists only what Dog itself defines, never what it inherits from a base class or from object.
class Animal:
legs = 4
class Cat(Animal):
sound = "meow"
print("legs" in vars(Cat)) # False
print(Cat.legs) # 4
print("legs" in vars(Animal)) # TrueCat finds legs only because lookup continues to the base class. The next chapter explains the order of that search.
Where each kind of name lives
| Kind of name | Typical location | Example |
|---|---|---|
| Data set on one object | Instance `__dict__` | `self.name = name` |
| Method | Class `__dict__` | `def bark(self): ...` |
| Value shared by all instances | Class `__dict__` | `species = "..."` |
| Name inherited from a base class | The base class's `__dict__` | `Animal.legs` |
How the search is laid out
The diagram shows the dictionaries consulted when you read d.species for an instance d of Dog, which inherits from object.
The instance sits at the top, with its own dictionary. The class type(d) is reached through the instance's type, not through d.__dict__, and it has a dictionary of its own. Base classes each have a dictionary too.
Reads and writes are not symmetric
This asymmetry causes more confusion than any other point in this chapter.
- A read searches the instance, then the class, then the bases.
- A write stores into the instance dictionary only.
So an instance attribute can hide a class attribute of the same name without changing it:
class Dog:
species = "Canis familiaris"
a = Dog()
b = Dog()
a.species = "wolf"
print(a.species) # wolf
print(b.species) # Canis familiaris
print(Dog.species) # Canis familiaris
del a.species # remove the shadowing entry
print(a.species) # Canis familiarisDeleting the instance entry makes the class value visible again, because it was never lost.
The augmented assignment trap
obj.count += 1 is a read followed by a write. It reads through the class if needed, then writes to the instance:
class Counter:
count = 0
c = Counter()
c.count += 1
print(c.count) # 1
print(Counter.count) # 0
print(c.__dict__) # {'count': 1}If you wanted a counter shared by all instances, write Counter.count += 1 (or type(self).count += 1 inside a method).
Shared mutable class attributes
Mutating an object that is stored on the class does not involve assignment, so no shadowing happens. Every instance sees the change:
class Bag:
items = [] # one list, shared by every instance
x = Bag()
y = Bag()
x.items.append("apple")
print(y.items) # ['apple']
print(y.__dict__) # {}For per-instance containers, create them in __init__ with self.items = [].
Inspecting namespaces
These tools help you see where a name lives:
vars(obj)orobj.__dict__: only that object's own namespace.dir(obj): a sorted list of names from the instance, its class, and the bases combined. It is meant for exploration and is not an exact record of what lookup will find.type(obj).__dict__: the class namespace."name" in vars(obj): whether the instance itself holds the name.
class P:
unit = "cm"
def __init__(self):
self.x = 1
p = P()
print("x" in vars(p), "unit" in vars(p)) # True False
print("x" in vars(type(p)), "unit" in vars(type(p))) # False TrueWhere this leads
You now have the storage model: values live in per-object dictionaries, and reads fall back from instance to class to bases. The open question is the exact order and the extra rules. Two examples show why it is open:
d.__dict__is not itself a key ind.__dict__. It is found on the class, through a mechanism this tutorial explains later.- Some class-level objects, such as properties, can take precedence over an instance dictionary entry of the same name.
The next chapter looks at how Python orders the search through the class hierarchy.
Exercise
Given the code below, what do the four print calls output, and what does vars(c) contain at the end?
class Config:
debug = False
tags = []
c = Config()
c.debug = True
c.tags.append("x")
print(Config.debug)
print(c.debug)
print(Config.tags)
print("tags" in vars(c))
Show answer
The outputs are False, True, ['x'], False. c.debug = True writes to the instance dictionary and shadows the class value, so Config.debug stays False. c.tags.append("x") reads tags from the class and mutates the shared list without any assignment, so Config.tags becomes ['x'] and "tags" is not in vars(c). At the end vars(c) is {'debug': True}.
Exercise
Why does Dog.__dict__["species"] = "wolf" raise a TypeError, and what should you write instead?
Show answer
Dog.__dict__ is a read-only mappingproxy, so item assignment is not supported. Use Dog.species = "wolf" or setattr(Dog, "species", "wolf"), which goes through the class's attribute machinery.