{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"dunder-methods","title":"Dunder methods: making your own objects work with len, for, in and ==","url":"https://addaly.com/learn/python-for-ai/dunder-methods","position":63,"of":89,"minutes":9,"answer":"Built-in syntax is dispatched to double-underscore methods (len() calls __len__, for calls __iter__, == calls __eq__) so implementing them makes a class feel native, and defining __eq__ without __hash__ silently makes instances unhashable.","keyIdea":"Built-in syntax is dispatched to double-underscore methods (len() calls __len__, for calls __iter__, == calls __eq__) so implementing them makes a class feel native, and defining __eq__ without __hash__ silently makes instances unhashable."},"body":{"format":"markdown","text":"## Syntax is a method call\n\nWhen you write `len(x)`, Python calls `x.__len__()`. When you write `for item in x`, Python calls `x.__iter__()`. `x == y` is `x.__eq__(y)`, `x[3]` is `x.__getitem__(3)`, and `x + y` is `x.__add__(y)`. The double-underscore names (\"dunder\") are hooks that built-in syntax reaches for, and a class that implements them behaves like a built-in type.\n\nYou have used two already: `__init__` and `__repr__`. Here are the ones that make a data-holding class pleasant to use, with the trap in each.\n\n## `__len__` and `__bool__`\n\n```python\nclass Conversation:\n    ...\n    def __len__(self):\n        return len(self.messages)\n```\n\nNow `len(conv)` works. So does something you may not want: `if conv:` is now false for an empty conversation, because when a class defines `__len__` and not `__bool__`, truthiness falls through to `len(x) != 0`. This is how empty lists and dicts are falsy. If you want an object to be truthy regardless, define `__bool__` returning `True`.\n\n## `__iter__`\n\n```python\n    def __iter__(self):\n        return iter(self.messages)\n```\n\n`for m in conv:` now walks the messages, and so does `list(conv)`, `any(... for m in conv)`, and unpacking. Returning `iter(self.messages)` delegates to the list's own iterator. A generator works too:\n\n```python\n    def __iter__(self):\n        for m in self.messages:\n            if m[\"role\"] != \"system\":\n                yield m\n```\n\nwhich hides the system prompt from anyone iterating. The next lesson covers what an iterator is underneath.\n\n## `__getitem__` and `__contains__`\n\n```python\n    def __getitem__(self, i):\n        return self.messages[i]\n```\n\n`conv[0]` and `conv[-1]` work, and so does `conv[1:3]`, because slices are passed to `__getitem__` as `slice` objects and the list handles them. A class with `__getitem__` and no `__iter__` is still iterable: Python calls `__getitem__` with 0, 1, 2 until `IndexError`. That is a fallback, not a design.\n\n`in` uses `__contains__` if present, otherwise iterates and compares. For a large collection, a `__contains__` backed by a set is the difference between O(1) and O(n).\n\n## `__eq__` and the hash rule\n\nThe default `==` on your own class is identity: two `Usage` objects with identical fields are unequal unless they are the same object. To compare by value:\n\n```python\n    def __eq__(self, other):\n        if not isinstance(other, Usage):\n            return NotImplemented\n        return (\n            self.input_tokens,\n            self.output_tokens,\n            self.model,\n        ) == (\n            other.input_tokens,\n            other.output_tokens,\n            other.model,\n        )\n```\n\nReturn `NotImplemented`, not `False`, for a type you cannot compare; that lets Python try the other operand's `__eq__` before giving up.\n\nNow the trap. The moment you define `__eq__`, Python sets `__hash__` to `None` on your class. Instances can no longer go in a set or be dict keys. The reason is a rule: objects that compare equal must have the same hash, and the default hash is based on identity, which your new `__eq__` no longer respects. Python cannot know what you meant, so it removes the hash rather than leave a broken one. Restore it yourself from the same fields:\n\n```python\n    def __hash__(self):\n        return hash(\n            (\n                self.input_tokens,\n                self.output_tokens,\n                self.model,\n            )\n        )\n```\n\nOnly do this for objects whose fields will not change after creation. A hash computed from mutable fields goes stale when a field changes, and a set containing such an object will fail to find it. This is why dataclasses give you `__hash__` only when `frozen=True`.\n\n## `__enter__` and `__exit__`\n\n```python\nclass Timer:\n    def __enter__(self):\n        self.start = time.perf_counter()\n        return self\n\n    def __exit__(self, exc_type, exc, tb):\n        self.elapsed = time.perf_counter() - self.start\n        return False\n```\n\n```python\nwith Timer() as t:\n    reply = provider.complete(messages)\nprint(f\"{t.elapsed:.2f}s\")\n```\n\n`with` calls `__enter__` at the top and `__exit__` at the bottom, including when the block raises. The three arguments to `__exit__` describe the exception, or are all `None`. Returning `False` lets the exception continue; returning `True` swallows it, which is almost never what you want. Context managers get their own lesson shortly.\n\n## `__str__` versus `__repr__`\n\n`__repr__` is for developers: unambiguous, ideally something you could paste back into the shell. `__str__` is for people: `print(x)` and f-strings use it, falling back to `__repr__` if it is missing. Write `__repr__` always; add `__str__` when a friendlier display is needed.\n\n## `__call__`\n\nAn object with `__call__` can be used like a function:\n\n```python\nclass Prompt:\n    def __init__(self, template):\n        self.template = template\n    def __call__(self, **kw):\n        return self.template.format(**kw)\n\ngreet = Prompt(\"Hello, {name}. Summarise: {text}\")\ngreet(name=\"Asha\", text=doc)\n```\n\nIt is how a class can be handed to code that expects a function while carrying state. Decorators in a later lesson lean on it.\n\n## Restraint\n\nEvery dunder you define is a promise that your object behaves like the built-in whose syntax it borrows. `__add__` on a `Conversation` that merges two conversations may seem clever, but a reader who sees `a + b` expects arithmetic-like behaviour (commutative, side-effect-free) and merging is neither. When the meaning is not obvious from the operator, a named method is kinder. `__len__`, `__iter__`, `__repr__`, `__eq__` with `__hash__`: those four carry no such risk and belong on almost every class that holds a collection.\n\n## Try this now\n\nGive `Conversation` a `__len__`, `__iter__` that skips the system message, and `__getitem__`. Then add `__eq__` to `Usage`, try to put one in a set, read the error, and add `__hash__`."},"check":{"question":"A developer adds `__eq__` to a `Document` class so that two documents with the same text compare equal. Afterwards, `seen = set(); seen.add(doc)` raises `TypeError: unhashable type: 'Document'`, though it worked before. What happened?","options":[{"text":"Sets require `__lt__` so they can keep members in order, and defining `__eq__` removed the default ordering.","correct":false,"tempting":"Sets are unordered and never use `__lt__`; membership is by hash and equality."},{"text":"`__eq__` must return a boolean, and the developer's version returned the compared string, which the set could not hash.","correct":false,"tempting":"The return value of `__eq__` is not what a set hashes; the error is raised before any comparison happens."},{"text":"Defining `__eq__` without `__hash__` sets `__hash__` to `None`, since equal objects must hash equally and the default identity hash cannot promise that.","correct":true},{"text":"Sets store only immutable objects, and adding `__eq__` marks a class as mutable in the interpreter's eyes, so every instance is refused from that point on regardless of its fields.","correct":false,"tempting":"Mutable objects can be set members if they hash; lists are excluded because they define no hash, not because of a mutability flag."}]},"prev":{"slug":"inheritance-and-composition","title":"Inheritance and composition: swapping one model provider for another","url":"https://addaly.com/learn/python-for-ai/inheritance-and-composition"},"next":{"slug":"the-iterator-protocol","title":"The iterator protocol: what for actually does, and why a generator is empty the second time","url":"https://addaly.com/learn/python-for-ai/the-iterator-protocol"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Dunder methods: making your own objects work with len, for, in and ==', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/dunder-methods (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Dunder methods: making your own objects work with len, for, in and ==","courseTitle":"Python, from Zero, for AI","module":{"index":7,"slug":"objects-and-the-shape-of-programs","title":"Objects, generators and the shape a larger program takes"},"answer":null,"keyIdea":"Built-in syntax is dispatched to double-underscore methods (len() calls __len__, for calls __iter__, == calls __eq__) so implementing them makes a class feel native, and defining __eq__ without __hash__ silently makes instances unhashable.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"syntax-is-a-method-call","runs":[{"text":"Syntax is a method call"}]},{"t":"p","runs":[{"text":"When you write "},{"text":"len(x)","code":true},{"text":", Python calls "},{"text":"x.__len__()","code":true},{"text":". When you write "},{"text":"for item in x","code":true},{"text":", Python calls "},{"text":"x.__iter__()","code":true},{"text":". "},{"text":"x == y","code":true},{"text":" is "},{"text":"x.__eq__(y)","code":true},{"text":", "},{"text":"x[3]","code":true},{"text":" is "},{"text":"x.__getitem__(3)","code":true},{"text":", and "},{"text":"x + y","code":true},{"text":" is "},{"text":"x.__add__(y)","code":true},{"text":". The double-underscore names (“dunder”) are hooks that built-in syntax reaches for, and a class that implements them behaves like a built-in type."}]},{"t":"p","runs":[{"text":"You have used two already: "},{"text":"__init__","code":true},{"text":" and "},{"text":"__repr__","code":true},{"text":". Here are the ones that make a data-holding class pleasant to use, with the trap in each."}]},{"t":"h2","id":"len-and-bool","runs":[{"text":"__len__","code":true},{"text":" and "},{"text":"__bool__","code":true}]},{"t":"code","lang":"python","label":"Python","text":"class Conversation:\n    ...\n    def __len__(self):\n        return len(self.messages)"},{"t":"p","runs":[{"text":"Now "},{"text":"len(conv)","code":true},{"text":" works. So does something you may not want: "},{"text":"if conv:","code":true},{"text":" is now false for an empty conversation, because when a class defines "},{"text":"__len__","code":true},{"text":" and not "},{"text":"__bool__","code":true},{"text":", truthiness falls through to "},{"text":"len(x) != 0","code":true},{"text":". This is how empty lists and dicts are falsy. If you want an object to be truthy regardless, define "},{"text":"__bool__","code":true},{"text":" returning "},{"text":"True","code":true},{"text":"."}]},{"t":"h2","id":"iter","runs":[{"text":"__iter__","code":true}]},{"t":"code","lang":"python","label":"Python","text":"    def __iter__(self):\n        return iter(self.messages)"},{"t":"p","runs":[{"text":"for m in conv:","code":true},{"text":" now walks the messages, and so does "},{"text":"list(conv)","code":true},{"text":", "},{"text":"any(... for m in conv)","code":true},{"text":", and unpacking. Returning "},{"text":"iter(self.messages)","code":true},{"text":" delegates to the list’s own iterator. A generator works too:"}]},{"t":"code","lang":"python","label":"Python","text":"    def __iter__(self):\n        for m in self.messages:\n            if m[\"role\"] != \"system\":\n                yield m"},{"t":"p","runs":[{"text":"which hides the system prompt from anyone iterating. The next lesson covers what an iterator is underneath."}]},{"t":"h2","id":"getitem-and-contains","runs":[{"text":"__getitem__","code":true},{"text":" and "},{"text":"__contains__","code":true}]},{"t":"code","lang":"python","label":"Python","text":"    def __getitem__(self, i):\n        return self.messages[i]"},{"t":"p","runs":[{"text":"conv[0]","code":true},{"text":" and "},{"text":"conv[-1]","code":true},{"text":" work, and so does "},{"text":"conv[1:3]","code":true},{"text":", because slices are passed to "},{"text":"__getitem__","code":true},{"text":" as "},{"text":"slice","code":true},{"text":" objects and the list handles them. A class with "},{"text":"__getitem__","code":true},{"text":" and no "},{"text":"__iter__","code":true},{"text":" is still iterable: Python calls "},{"text":"__getitem__","code":true},{"text":" with 0, 1, 2 until "},{"text":"IndexError","code":true},{"text":". That is a fallback, not a design."}]},{"t":"p","runs":[{"text":"in","code":true},{"text":" uses "},{"text":"__contains__","code":true},{"text":" if present, otherwise iterates and compares. For a large collection, a "},{"text":"__contains__","code":true},{"text":" backed by a set is the difference between O(1) and O(n)."}]},{"t":"h2","id":"eq-and-the-hash-rule","runs":[{"text":"__eq__","code":true},{"text":" and the hash rule"}]},{"t":"p","runs":[{"text":"The default "},{"text":"==","code":true},{"text":" on your own class is identity: two "},{"text":"Usage","code":true},{"text":" objects with identical fields are unequal unless they are the same object. To compare by value:"}]},{"t":"code","lang":"python","label":"Python","text":"    def __eq__(self, other):\n        if not isinstance(other, Usage):\n            return NotImplemented\n        return (\n            self.input_tokens,\n            self.output_tokens,\n            self.model,\n        ) == (\n            other.input_tokens,\n            other.output_tokens,\n            other.model,\n        )"},{"t":"p","runs":[{"text":"Return "},{"text":"NotImplemented","code":true},{"text":", not "},{"text":"False","code":true},{"text":", for a type you cannot compare; that lets Python try the other operand’s "},{"text":"__eq__","code":true},{"text":" before giving up."}]},{"t":"p","runs":[{"text":"Now the trap. The moment you define "},{"text":"__eq__","code":true},{"text":", Python sets "},{"text":"__hash__","code":true},{"text":" to "},{"text":"None","code":true},{"text":" on your class. Instances can no longer go in a set or be dict keys. The reason is a rule: objects that compare equal must have the same hash, and the default hash is based on identity, which your new "},{"text":"__eq__","code":true},{"text":" no longer respects. Python cannot know what you meant, so it removes the hash rather than leave a broken one. Restore it yourself from the same fields:"}]},{"t":"code","lang":"python","label":"Python","text":"    def __hash__(self):\n        return hash(\n            (\n                self.input_tokens,\n                self.output_tokens,\n                self.model,\n            )\n        )"},{"t":"p","runs":[{"text":"Only do this for objects whose fields will not change after creation. A hash computed from mutable fields goes stale when a field changes, and a set containing such an object will fail to find it. This is why dataclasses give you "},{"text":"__hash__","code":true},{"text":" only when "},{"text":"frozen=True","code":true},{"text":"."}]},{"t":"h2","id":"enter-and-exit","runs":[{"text":"__enter__","code":true},{"text":" and "},{"text":"__exit__","code":true}]},{"t":"code","lang":"python","label":"Python","text":"class Timer:\n    def __enter__(self):\n        self.start = time.perf_counter()\n        return self\n\n    def __exit__(self, exc_type, exc, tb):\n        self.elapsed = time.perf_counter() - self.start\n        return False"},{"t":"code","lang":"python","label":"Python","text":"with Timer() as t:\n    reply = provider.complete(messages)\nprint(f\"{t.elapsed:.2f}s\")"},{"t":"p","runs":[{"text":"with","code":true},{"text":" calls "},{"text":"__enter__","code":true},{"text":" at the top and "},{"text":"__exit__","code":true},{"text":" at the bottom, including when the block raises. The three arguments to "},{"text":"__exit__","code":true},{"text":" describe the exception, or are all "},{"text":"None","code":true},{"text":". Returning "},{"text":"False","code":true},{"text":" lets the exception continue; returning "},{"text":"True","code":true},{"text":" swallows it, which is almost never what you want. Context managers get their own lesson shortly."}]},{"t":"h2","id":"str-versus-repr","runs":[{"text":"__str__","code":true},{"text":" versus "},{"text":"__repr__","code":true}]},{"t":"p","runs":[{"text":"__repr__","code":true},{"text":" is for developers: unambiguous, ideally something you could paste back into the shell. "},{"text":"__str__","code":true},{"text":" is for people: "},{"text":"print(x)","code":true},{"text":" and f-strings use it, falling back to "},{"text":"__repr__","code":true},{"text":" if it is missing. Write "},{"text":"__repr__","code":true},{"text":" always; add "},{"text":"__str__","code":true},{"text":" when a friendlier display is needed."}]},{"t":"h2","id":"call","runs":[{"text":"__call__","code":true}]},{"t":"p","runs":[{"text":"An object with "},{"text":"__call__","code":true},{"text":" can be used like a function:"}]},{"t":"code","lang":"python","label":"Python","text":"class Prompt:\n    def __init__(self, template):\n        self.template = template\n    def __call__(self, **kw):\n        return self.template.format(**kw)\n\ngreet = Prompt(\"Hello, {name}. Summarise: {text}\")\ngreet(name=\"Asha\", text=doc)"},{"t":"p","runs":[{"text":"It is how a class can be handed to code that expects a function while carrying state. Decorators in a later lesson lean on it."}]},{"t":"h2","id":"restraint","runs":[{"text":"Restraint"}]},{"t":"p","runs":[{"text":"Every dunder you define is a promise that your object behaves like the built-in whose syntax it borrows. "},{"text":"__add__","code":true},{"text":" on a "},{"text":"Conversation","code":true},{"text":" that merges two conversations may seem clever, but a reader who sees "},{"text":"a + b","code":true},{"text":" expects arithmetic-like behaviour (commutative, side-effect-free) and merging is neither. When the meaning is not obvious from the operator, a named method is kinder. "},{"text":"__len__","code":true},{"text":", "},{"text":"__iter__","code":true},{"text":", "},{"text":"__repr__","code":true},{"text":", "},{"text":"__eq__","code":true},{"text":" with "},{"text":"__hash__","code":true},{"text":": those four carry no such risk and belong on almost every class that holds a collection."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Give "},{"text":"Conversation","code":true},{"text":" a "},{"text":"__len__","code":true},{"text":", "},{"text":"__iter__","code":true},{"text":" that skips the system message, and "},{"text":"__getitem__","code":true},{"text":". Then add "},{"text":"__eq__","code":true},{"text":" to "},{"text":"Usage","code":true},{"text":", try to put one in a set, read the error, and add "},{"text":"__hash__","code":true},{"text":"."}]}],"check":{"question":[{"text":"A developer adds "},{"text":"__eq__","code":true},{"text":" to a "},{"text":"Document","code":true},{"text":" class so that two documents with the same text compare equal. Afterwards, "},{"text":"seen = set(); seen.add(doc)","code":true},{"text":" raises "},{"text":"TypeError: unhashable type: 'Document'","code":true},{"text":", though it worked before. What happened?"}],"options":[{"text":[{"text":"Sets require "},{"text":"__lt__","code":true},{"text":" so they can keep members in order, and defining "},{"text":"__eq__","code":true},{"text":" removed the default ordering."}],"correct":false,"tempting":[{"text":"Sets are unordered and never use "},{"text":"__lt__","code":true},{"text":"; membership is by hash and equality."}]},{"text":[{"text":"__eq__","code":true},{"text":" must return a boolean, and the developer’s version returned the compared string, which the set could not hash."}],"correct":false,"tempting":[{"text":"The return value of "},{"text":"__eq__","code":true},{"text":" is not what a set hashes; the error is raised before any comparison happens."}]},{"text":[{"text":"Defining "},{"text":"__eq__","code":true},{"text":" without "},{"text":"__hash__","code":true},{"text":" sets "},{"text":"__hash__","code":true},{"text":" to "},{"text":"None","code":true},{"text":", since equal objects must hash equally and the default identity hash cannot promise that."}],"correct":true,"tempting":null},{"text":[{"text":"Sets store only immutable objects, and adding "},{"text":"__eq__","code":true},{"text":" marks a class as mutable in the interpreter’s eyes, so every instance is refused from that point on regardless of its fields."}],"correct":false,"tempting":[{"text":"Mutable objects can be set members if they hash; lists are excluded because they define no hash, not because of a mutability flag."}]}],"order":[3,1,0,2],"why":null},"prev":{"slug":"inheritance-and-composition","title":"Inheritance and composition: swapping one model provider for another","minutes":9},"next":{"slug":"the-iterator-protocol","title":"The iterator protocol: what for actually does, and why a generator is empty the second time","minutes":9}}}