Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Class __dict__: Instance and Class Namespaces

Python's __dict__ namespaces hold instance and class attributes. Learn how attribute lookup uses them and when __slots__ removes the instance dictionary.

~4 min readPython
#python#__dict__#object model#attribute access
Diagram showing a Python class object and an instance, each with its own __dict__ mapping attribute names to values.

The __dict__ attribute is central to how a Python class stores state. For an instance of a normal user-defined class, obj.__dict__ is a plain dictionary holding whatever attributes were assigned to that instance. The class object also has a __dict__, but it is a separate mapping that holds methods, class variables, and descriptors.

What __dict__ Holds on a Class vs an Instance

For instances of user-defined classes, __dict__ is a plain dictionary. When you assign self.x = 2 inside __init__, Python writes the key 'x' with value 2 into that dictionary.

python
class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(2, 3) print(p.__dict__) # {'x': 2, 'y': 3}

The class object itself also has a __dict__, but it is a different object. It holds the class namespace: methods, class variables, and descriptors. In CPython this namespace is wrapped in a mappingproxy, so you cannot assign entries through Point.__dict__['label'] = ... directly. Normal class assignment such as Point.label = ... still works.

python
class Point: label = 'point' def __init__(self, x, y): self.x = x self.y = y def magnitude(self): return (self.x ** 2 + self.y ** 2) ** 0.5 print(Point.__dict__.keys()) # Representative output (the exact keys vary by Python version): # dict_keys(['__module__', '__qualname__', 'label', '__init__', # 'magnitude', '__dict__', '__weakref__', '__doc__'])

The instance __dict__ and the class __dict__ are separate. Assigning p.label = 'other' creates an entry in p.__dict__ and shadows the class-level label for that instance only.

How Attribute Lookup Uses __dict__

When you read p.magnitude, Python does not search only p.__dict__. For ordinary names, attribute lookup checks the instance dictionary first, then walks the method resolution order of the class and checks each class's __dict__ in turn. This is why methods and class variables are visible from instances even though they are not stored in the instance namespace.

One caveat is that data descriptors on the class, such as property, take precedence over the instance dictionary. A plain method or class variable is not a data descriptor, so an instance attribute with the same name shadows it.

python
p = Point(2, 3) print(p.__dict__) # {'x': 2, 'y': 3} print('magnitude' in p.__dict__) # False print(Point.__dict__['magnitude']) # <function Point.magnitude at ...>

The lookup order matters when an instance attribute has the same name as a class attribute. The instance value wins because the instance dictionary is checked first when no data descriptor is involved.

Modifying __dict__ Directly

Because the instance __dict__ is a plain dictionary, you can read and write it directly.

python
p = Point(2, 3) p.__dict__['x'] = 10 print(p.x) # 10 p.__dict__['z'] = 5 print(p.z) # 5

This works, but it bypasses __setattr__ and any descriptor protocol on the class. If your class relies on __setattr__ for validation or coercion, direct writes to __dict__ will skip that logic. Direct manipulation is useful mainly for metaprogramming, debugging, or serialization code that needs to inspect or rebuild object state.

The class-level __dict__ is a mappingproxy, so direct item assignment like Point.__dict__['label'] = 'other' raises TypeError. You can still change class attributes with setattr(Point, 'label', 'other') or with normal assignment Point.label = 'other'.

__slots__ and When __dict__ Disappears

Defining __slots__ on a class changes how instances store attributes. Instead of a per-instance dictionary, Python allocates fixed slots for the listed attribute names.

python
class Point: __slots__ = ('x', 'y') def __init__(self, x, y): self.x = x self.y = y p = Point(2, 3) print(p.__dict__) # AttributeError: 'Point' object has no attribute '__dict__'

With __slots__ and without '__dict__' listed in it, instances no longer have a __dict__ (unless a base class supplies one). Attempting to assign an attribute not listed in __slots__ raises AttributeError. This is the tradeoff: you lose dynamic attribute assignment and gain a smaller memory footprint.

You can opt back into a dictionary by including '__dict__' in __slots__:

python
class Point: __slots__ = ('x', 'y', '__dict__')

This restores the instance __dict__ while still keeping the compact slots for x and y. In that case, attributes not named in __slots__ can be created in the instance dictionary.

Memory and Performance Implications

The main reason to use __slots__ is memory. A dictionary has significant overhead: the hash table, the entries, and the capacity that grows as keys are added. For a small object with two or three attributes, the dictionary can dominate the object's memory footprint. When a program holds many such objects, replacing the dictionary with slots can reduce memory usage substantially.

The performance effect of __slots__ on attribute access is usually small. Attribute reads through slots avoid a dictionary lookup and may be slightly faster, but the difference is rarely the bottleneck in real code. The decision to use __slots__ should be driven by memory constraints or by the need to prevent dynamic attribute creation, not by micro-optimization.

There is also a correctness angle. With __slots__ and no __dict__ fallback, misspelled attribute assignments fail fast instead of silently creating new attributes. That can be valuable in code where attribute names must stay consistent.

Practical Patterns and Edge Cases

One common pattern is using __dict__ to convert an object to a dictionary for serialization:

python
def to_dict(obj): return dict(obj.__dict__)

This works for simple objects but fails for instances of classes with __slots__. A more robust approach also reads slot names, including inherited slots:

python
def to_dict(obj): result = {} for cls in type(obj).__mro__: for name in getattr(cls, '__slots__', ()): if name not in ('__dict__', '__weakref__'): result[name] = getattr(obj, name) if hasattr(obj, '__dict__'): for key, value in obj.__dict__.items(): result.setdefault(key, value) return result

Another edge case: the __dict__ of a module is a regular dictionary, which is why module.attribute and module.__dict__['attribute'] are equivalent. Functions also have a __dict__, used for arbitrary attributes attached to the function object.

Finally, for a class that uses instance dictionaries, the class namespace includes an entry named __dict__; SomeClass.__dict__['__dict__'] is the descriptor that provides those dictionaries. Removing or replacing it is not something you should do in normal code.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.