Python's Data Model: How Special Methods Shape Custom Objects
Every Python object you have ever used, from a humble list to a datetime, behaves the way it does because of the Python data model. It is the contract that tells the interpreter what len(x), x + y, x[0], for item in x, with x: and print(x) should mean for a given object. The mechanism behind that contract is a set of special methods, also called dunder methods (short for "double underscore") or magic methods.
If you can read and write special methods, you can build classes that feel native to the language. They work with built-in functions, operators, loops, and standard-library tools without any adapter code. This guide covers how the interpreter calls special methods, which ones matter most, and how to avoid the mistakes that cause subtle bugs. Every concept comes with runnable examples.
Key takeaways
The Python data model defines how objects interact with language syntax and built-in functions. Special methods are how your classes plug into it.
You almost never call special methods directly. You write len(obj), and Python calls type(obj).__len__(obj) for you.
Special methods are looked up on the , not on the instance. Assigning does not work.
Return NotImplemented, instead of raising an exception, from binary operators when you do not recognize the other operand.
If you define __eq__, think about __hash__ in the same moment. Python sets __hash__ to None when you define __eq__ alone.
Implementing __len__ and __getitem__ alone gives you iteration, membership tests, and reversed() for free.
Prefer @dataclass when you only need a data container, because it generates the common special methods correctly.
What is the Python data model?
The Python data model is the part of the language reference that describes objects, types, and the hooks the interpreter uses to give them behavior. A useful way to think about it: Python is a framework, and your classes are plugins. The framework calls your code at well-defined moments, such as when an object is created, compared, printed, indexed, iterated, or garbage collected. Special methods are the names of those moments.
Each line triggers a special method on list: __len__, __getitem__, and __contains__. The built-in list type is not magic. It simply implements the protocol, and so can any class you write.
That is the central idea of the data model: built-in behavior is not reserved for built-in types. When your class implements the right special methods, it becomes a first-class citizen of the language.
Why this matters in real projects
Learning the data model pays off in several practical ways:
Readable APIs.cart.total, len(cart), and for item in cart are easier to read than cart.get_total(), cart.count_items(), and cart.get_item_list().
Compatibility. Functions such as sorted(), sum(), max(), enumerate(), and zip() work with any object that implements the right protocol.
Fewer bugs. A correct __repr__ makes debugging and logging far easier, and a correct __eq__/__hash__ pair prevents strange behavior in sets and dictionaries.
Framework fluency. ORMs, web frameworks, and testing libraries lean heavily on special methods. Understanding them makes library source code readable.
The same idea, a typed contract that tools can rely on, shows up in other languages too. If you work with TypeScript, our guide on type-safe event emitters with generic event maps explores contract-first design from a different angle.
How Python calls special methods
Special methods are meant to be invoked by the interpreter, not by your own code. Compare these two lines:
text = "data model"
print(len(text)) # idiomatic
print(text.__len__()) # works, but unidiomatic
Both print 10, but only the first expresses intent clearly. Calling len() also allows Python to perform extra validation, such as checking that __len__ returns a non-negative integer. For some built-ins, such as iter(), len(), and str(), it can also take faster internal paths.
Lookup happens on the type, not the instance
This detail trips up many developers. For implicit special-method calls, Python looks the method up on the class (the type of the object), bypassing the instance dictionary. The language reference documents this as special method lookup.
class Demo:
pass
d = Demo()
d.__len__ = lambda: 5
len(d) # TypeError: object of type 'Demo' has no len()
Even though d has a __len__ attribute, len(d) ignores it because Demo does not define __len__ on the class. This design is what makes special methods predictable and fast, and it is why monkey-patching a single instance cannot change how operators or built-ins treat it.
A quick map from syntax to special methods
The table below covers the most common correspondences. Treat it as a mental index. The complete catalogue lives in the special method names section of the language reference.
What you write
What Python calls
Purpose
Cls(...)
__new__, then __init__
Create and initialize an instance
repr(x)
__repr__
Unambiguous, developer-facing text
str(x), print(x)
__str__
Readable, user-facing text
format(x, spec), f-strings
__format__
Custom format specifications
x == y, x < y
__eq__, __lt__, and related
Comparison
hash(x)
__hash__
Use as dict key or set member
bool(x), if x:
__bool__, else __len__
Truthiness
x + y, x * y
__add__, __mul__ (and reflected forms)
Arithmetic
len(x)
__len__
Size of a container
x[i], x[a:b]
__getitem__
Indexing and slicing
for a in x
__iter__, __next__
Iteration
a in x
__contains__
Membership test
x(...)
__call__
Make an object callable
with x:
__enter__, __exit__
Context management
x.name (missing)
__getattr__
Fallback attribute access
Object creation and representation
__new__ and __init__
Most classes only define __init__, which initializes an object after it exists. The method that actually creates the object is __new__, a static method that receives the class and returns a new instance. You rarely need __new__, but it is the right tool for immutable types and for controlling instance creation, as in singletons or caching.
class Meters(float):
def __new__(cls, value):
if value < 0:
raise ValueError("Meters cannot be negative")
return super().__new__(cls, value)
print(Meters(3.5)) # 3.5
Meters(-1) # ValueError: Meters cannot be negative
Because float is immutable, its value must be fixed at creation time, so validation belongs in __new__. For ordinary mutable classes, keep to __init__.
__repr__ versus __str__
These two methods are the most important representation hooks, and confusing them is common.
__repr__ should return an unambiguous string aimed at developers. When practical, it should look like valid code that recreates the object.
__str__ should return a readable string aimed at end users.
If you only implement one, implement __repr__. When a class defines __repr__ but not __str__, Python falls back to __repr__ for str() and print(). The reverse does not hold.
Notice the last line. Containers display their elements using repr(), which is why a good __repr__ matters in logs, tracebacks, and debugger output. The !r conversion inside the f-string calls repr() on each field, so strings appear with quotes and the output stays unambiguous.
Reading about special methods only goes so far. The best way to internalize them is to build one class that uses many of them together. Here is a small immutable two-dimensional vector.
v = Vector2D(3, 4)
w = Vector2D(1, 2)
print(v) # (3.0, 4.0)
print(repr(v)) # Vector2D(3.0, 4.0)
print(f"{v:.1f}") # (3.0, 4.0)
print(abs(v)) # 5.0
print(v + w) # (4.0, 6.0)
print(v * 2) # (6.0, 8.0)
print(2 * v) # (6.0, 8.0)
print(-v) # (-3.0, -4.0)
print(bool(Vector2D())) # False
x, y = v # unpacking works because of __iter__
print({v, Vector2D(3, 4)}) # a set with one element
Several design decisions here deserve attention.
Returning NotImplemented instead of raising
Look at __add__. When the other operand is not a Vector2D, the method returns NotImplemented, a special singleton, rather than raising TypeError. This signals to Python that this class does not know how to handle the operation, and Python then tries the reflected method on the other operand (__radd__). If neither side can handle it, Python raises the appropriate TypeError itself.
v + 5
# TypeError: unsupported operand type(s) for +: 'Vector2D' and 'int'
Returning NotImplemented keeps your classes cooperative with other types. It is also the reason 2 * v works: int.__mul__ returns NotImplemented for a Vector2D, so Python falls back to Vector2D.__rmul__. The operator-related methods are described under emulating numeric types.
Using type(self) instead of a hard-coded class name
Creating results with type(self)(...) instead of Vector2D(...) means a subclass of Vector2D returns instances of itself from arithmetic. It is a small habit that prevents surprising downcasts.
Why __eq__ and __hash__ travel together
Two objects that compare equal must have the same hash if they are going to be used in sets or as dictionary keys. Python enforces part of this contract for you. If a class defines __eq__ and does not define __hash__, Python sets __hash__ to None, which makes instances unhashable.
class Broken:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, Broken) and self.n == other.n
{Broken(1)} # TypeError: unhashable type: 'Broken'
This is intentional protection. Hashing a mutable object whose equality depends on changing fields can silently corrupt a set or dictionary. In Vector2D, the fields are read-only, so hashing them is safe. Read the rules in the documentation for object.__hash__ and object.__eq__.
Truthiness: __bool__ and the __len__ fallback
When you write if obj:, Python calls __bool__. If that method is missing, it calls __len__ and treats 0 as false. If neither exists, the object is always truthy. This is why empty lists, dictionaries, and strings are falsy, and it is why you can make your own containers behave the same way without writing __bool__.
Rich comparison and ordering
Python's six comparison operators map to six methods: __eq__, __ne__, __lt__, __le__, __gt__, and __ge__. In practice you rarely need all six. By default, __ne__ inverts the result of __eq__, and the standard library can generate the rest from a minimal set.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def _key(self):
return (self.major, self.minor)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._key() == other._key()
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._key() < other._key()
def __hash__(self):
return hash(self._key())
print(Version(1, 2) < Version(1, 10)) # True
print(Version(2, 0) >= Version(1, 99)) # True
print(sorted([Version(2, 0), Version(1, 5), Version(1, 10)])[0]._key()) # (1, 5)
The functools.total_ordering decorator fills in __le__, __gt__, and __ge__ from __eq__ and __lt__. It is convenient, though the generated methods can be slightly slower than hand-written ones. For performance-critical code, write them yourself or use a dataclass with order=True.
Comparing a tuple key, as _key() does here, is a reliable way to avoid writing repetitive comparison logic by hand.
Making containers: the sequence and mapping protocols
Container behavior is where special methods feel most powerful. A handful of methods can turn a custom class into something that works with len(), slicing, loops, in, sorted(), and more.
We never wrote __iter__, __contains__, or __reversed__, yet iteration, membership tests, and reversed() all work. Python falls back to the old sequence protocol: if a class has __getitem__ that accepts integer indexes starting from zero, Python can iterate by calling it with 0, 1, 2, and so on until it raises IndexError. Membership falls back to iteration, and reversed() uses __len__ together with __getitem__.
Slicing works because Python passes a slice object to __getitem__. Returning type(self)(...) from a slice, as above, keeps the slice the same type as the original, which is what built-in sequences do for lists and tuples.
Being explicit with __iter__ and __contains__
Relying on fallbacks is fine for small classes, but explicit methods are clearer and often faster. Defining __iter__ is also required if your container does not use integer indexes.
This class now behaves like a read-only mapping. For full mapping or sequence behavior, you can also inherit from the abstract base classes in collections.abc, such as Sequence, Mapping, or MutableMapping. They require a small set of abstract methods from you and supply many others, including get, keys, items, index, and count, as mixin methods.
Writing and deleting items
To support assignment and deletion, add __setitem__ and __delitem__. Use IndexError for sequences with out-of-range positions and KeyError for mappings with missing keys, because callers and built-in helpers rely on those exception types.
Making objects callable with __call__
A class that defines __call__ produces instances you can call like functions. This is useful when a function needs to remember state or configuration.
Callable objects are common in decorators implemented as classes, in strategy patterns, and in libraries where configuration objects double as functions. See object.__call__.
Context managers: __enter__ and __exit__
The with statement relies on two special methods. __enter__ runs when the block begins, and its return value is bound by as. __exit__ runs when the block ends, even if an exception occurred.
import time
class Timer:
def __enter__(self):
self._start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self._start
return False # do not suppress exceptions
with Timer() as t:
sum(range(1_000_000))
print(f"Took {t.elapsed:.4f} seconds")
If __exit__ returns a truthy value, Python suppresses the exception that triggered it. Return False or None unless suppressing a specific exception is your explicit goal. The details are in the documentation for with statement context managers. For simple cases, the contextlib.contextmanager decorator can create one from a generator function.
Controlling attribute access
Attribute access has its own set of special methods, and mixing them up is a frequent source of bugs.
__getattribute__ is called for every attribute lookup.
__getattr__ is called only after normal lookup fails.
__setattr__ is called for every assignment.
__delattr__ is called when an attribute is deleted.
__dir__ customizes what dir(obj) returns.
In most cases __getattr__ is the safe choice, because it only handles the missing-attribute case.
class Config:
def __init__(self, **values):
self._values = dict(values)
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)
try:
return self._values[name]
except KeyError:
raise AttributeError(
f"{type(self).__name__!r} object has no attribute {name!r}"
) from None
def __dir__(self):
return sorted(set(super().__dir__()) | set(self._values))
cfg = Config(host="localhost", port=8080)
print(cfg.host) # localhost
print(cfg.port) # 8080
cfg.timeout # AttributeError: 'Config' object has no attribute 'timeout'
Two details matter here. First, the guard for names starting with an underscore prevents infinite recursion. Without it, a lookup of _values before it is set, which can happen during copying or unpickling, would call __getattr__, which would look up _values again, and so on. Second, raising AttributeError for unknown names, rather than returning None, keeps hasattr() and getattr(obj, name, default) working correctly.
Be careful with __getattribute__ and __setattr__. Inside them, reach attributes through super().__getattribute__(name) or super().__setattr__(name, value), never through plain self.attr, which would trigger the same method again.
Properties and descriptors
Properties, classmethod, staticmethod, and bound methods are all built on the descriptor protocol: objects that define __get__, and optionally __set__, __delete__, and __set_name__. When you write @property, you are using a ready-made descriptor. If you find yourself repeating validation logic across many attributes, writing your own descriptor lets you reuse it. The official Descriptor How-To Guide is the best next read on this topic.
Special methods and dataclasses
Writing __init__, __repr__, __eq__, and ordering methods by hand gets repetitive for plain data holders. The dataclasses module generates them from annotated fields.
With frozen=True and the default eq=True, the decorator also generates a consistent __hash__, so frozen dataclass instances are usable as dictionary keys. Use a dataclass when your class is mainly data. Write special methods by hand when you need custom behavior, such as Vector2D arithmetic or container semantics.
Common mistakes and how to avoid them
Calling dunder methods directly. Prefer len(x), str(x), and x + y over x.__len__(), x.__str__(), and x.__add__(y). The built-in form handles fallbacks, validation, and reflected operations.
Inventing your own dunder names. Names that begin and end with double underscores are reserved for Python. A custom method named __total__ will not break today, but it can collide with a future language feature and it confuses readers. Use a normal name or a single leading underscore.
Defining __eq__ without thinking about __hash__. Decide deliberately whether instances should be hashable. If they are mutable, leaving them unhashable is usually correct.
Raising TypeError from binary operators instead of returning NotImplemented. Raising early blocks the other operand's reflected method and breaks cooperation with other types.
Returning the wrong type from special methods.__len__ must return a non-negative integer, __bool__ must return a bool, and __repr__ and __str__ must return strings. Violations raise TypeError at call time.
Using a mutable object as a hash key. If fields that participate in __eq__ and __hash__ can change after the object is placed in a set, lookups will fail unpredictably.
Unguarded __getattr__. Always raise AttributeError for names you do not handle, and guard private or internal names to avoid recursion.
Writing __del__ for resource cleanup. Finalizer timing is not guaranteed. Use context managers (__enter__/__exit__) or explicit close() methods for files, sockets, and locks.
Skipping __repr__. The default output, such as <Product object at 0x...>, tells you almost nothing when something goes wrong.
Best practices checklist
Always implement __repr__. Add __str__ only when a friendlier display genuinely differs.
Keep __eq__, __hash__, and ordering methods consistent with each other.
Make value-like classes immutable when practical, using __slots__, read-only properties, or frozen dataclasses.
Return NotImplemented for unsupported operand types in binary operators and comparisons.
Implement the smallest protocol that satisfies your use case, then lean on collections.abc for the rest.
Use type(self) when constructing results so subclasses behave correctly.
Document unusual semantics in the class docstring, particularly for operators, because readers expect them to follow mathematical or built-in conventions.
Write unit tests for special methods. They are public behavior, even though callers rarely invoke them by name.
When generating test data or inspecting serialized output from your objects, a JSON formatter and validator is a quick way to check that structures look the way you expect.
Frequently asked questions
What is the Python data model?
The Python data model is the set of rules, described in the language reference, that defines how objects behave with built-in functions, operators, and statements. Classes customize that behavior by implementing special methods such as __len__, __getitem__, and __add__.
Are special methods, dunder methods, and magic methods the same thing?
Yes. "Special methods" is the term used in the official documentation. "Dunder methods" is a nickname from "double underscore", and "magic methods" is an informal name that emphasizes how they seem to work behind the scenes.
What is the difference between __str__ and __repr__?
__repr__ returns an unambiguous, developer-oriented string, ideally one that could recreate the object. __str__ returns a readable string for end users. If only __repr__ is defined, Python uses it for both.
Why does __eq__ make my class unhashable?
When a class defines __eq__ without defining __hash__, Python sets __hash__ to None. This prevents mutable objects from being placed in hash-based collections where changing them would corrupt lookups. Define __hash__ explicitly if your objects are effectively immutable.
Do I need to define __iter__ if I already have __getitem__?
Not strictly. Python can iterate using __getitem__ with integer indexes starting at zero. Defining __iter__ is clearer, works for non-integer keys, and is the recommended approach for new code.
When should I use __getattr__ instead of __getattribute__?
Use __getattr__ in almost every case. It runs only when normal attribute lookup fails, so it is simpler and safer. __getattribute__ runs on every access and is easy to get wrong.
Can I add special methods to an existing object after creating it?
Not in a way the interpreter will honor. Implicit special-method calls are looked up on the type, so assigning a function to an instance attribute has no effect on operators or built-ins. You would need to define the method on the class.
Conclusion
The Python data model is the quiet engine behind the language's most readable code. Once you understand that len(x), x[0], x + y, for item in x, and with x: are all just protocol calls, writing custom classes stops being guesswork. You choose which protocols your object supports, implement the matching special methods carefully, and the rest of Python, including its built-ins, standard library, and third-party packages, works with your class naturally.
A good way to practice is to take a class you already maintain and add a meaningful __repr__, a consistent __eq__ and __hash__, and __len__ or __iter__ where they make sense. Then read through the special method names reference and pick one protocol you have never implemented. Small steps like these gradually turn Python's data model from trivia into one of your strongest design tools.
3Docker Sessions Lost After Redeploy? Fix In-Memory Storage