Le contrat __hash__ / __eq__ : l'objet mutable qu'on ne doit jamais hacher The __hash__ / __eq__ pact: the mutable object you must never hash

Un dict cherche une clé en deux temps : hash() choisit le compartiment, == confirme l'identité dedans. Casse l'accord entre les deux — deux objets égaux avec des hash différents — et le dict cherche au bon endroit un objet qui n'y est jamais rangé. C'est pour ça qu'une liste est unhashable : elle mute, et un objet qui mute après avoir été haché se perd dans son propre compartiment. A dict finds a key in two steps: hash() picks the bucket, == confirms identity inside it. Break the deal between the two — two equal objects with different hashes — and the dict searches the right spot for an object that was never filed there. That's why a list is unhashable: it mutates, and an object that mutates after being hashed loses itself in its own bucket.

Audience
Dev qui a défini __eq__ sur une classe et s'est heurté à un TypeError, ou pire, à un bug silencieux Dev who defined __eq__ on a class and hit a TypeError — or worse, a silent bug
ChapitresChapters
5
LectureReading
≈ 19 min
NiveauLevel
●●●○
Date
Juil 2026 Jul 2026

Data modelHashDict & Set

SommaireContents ·
№ 01CadrageFraming3 min

Un dict ne cherche pas une clé — il la localise, en deux temps.A dict doesn't search for a key — it locates it, in two steps.

Le numéro précédent a posé le couple __eq__/__hash__ comme un contrat couplé, sans dire pourquoi le langage y tient tant. Voici la raison : un dict ou un set ne compare pas la clé cherchée à toutes les clés existantes, un par un — ce serait aussi lent qu'une liste. Il appelle hash(clé) pour obtenir un entier, s'en sert pour sauter directement à un compartiment interne, et ne compare avec == qu'à l'intérieur de ce compartiment, pour départager d'éventuelles collisions. La rapidité légendaire du dict repose entièrement sur ce raccourci — et le raccourci suppose une règle stricte.The previous issue set up the __eq__/__hash__ pair as a coupled contract, without saying why the language cares so much. Here's why: a dict or set doesn't compare a sought key against every existing key, one by one — that would be as slow as a list. It calls hash(key) to get an integer, uses it to jump straight to an internal bucket, and only compares with == inside that bucket, to break ties on collisions. The dict's legendary speed rests entirely on that shortcut — and the shortcut assumes a strict rule.

hash() choisit le compartiment, == confirme dedanshash() picks the bucket, == confirms inside it
vus = {"alice", "bob", "carol"}
"bob" in vus
# 1. hash("bob")  -> un entier          -> choisit un compartiment
# 2. dans ce compartiment, Python compare "bob" == chaque clé qui s'y trouve
# 3. une égalité confirme -> True. Sans elle -> False, même compartiment ou pas.

# Un set ne parcourt PAS ses éléments un par un : il saute directement
# au compartiment désigné par le hash, puis ne compare qu'à l'intérieur.
Le sous-réflexe du numéroThis issue's sub-reflex

Avant de mettre un objet dans un set ou comme clé de dict, demande : son hash restera-t-il collé à son égalité, pour toute sa vie dans cette structure ? Si la réponse dépend d'un état qui peut changer, l'objet n'a rien à faire là.Before putting an object in a set or as a dict key, ask: will its hash stay glued to its equality, for its whole life inside that structure? If the answer depends on state that can change, the object has no business being there.

Le hash n'est pas une signature.The hash isn't a signature.

hash() ne prouve rien à lui seul : deux objets différents peuvent partager un hash (collision, normale et gérée). C'est == qui tranche. Le hash ne sert qu'à réduire la recherche à une poignée de candidats — sa seule obligation est de ne jamais séparer deux objets égaux dans deux compartiments différents.hash() alone proves nothing: two different objects can share a hash (a collision, normal and handled). == is what settles it. The hash only narrows the search to a handful of candidates — its one obligation is to never split two equal objects into different buckets.

№ 02La règleThe rule5 min

Deux objets égaux doivent avoir le même hash. L'inverse n'est pas exigé.Two equal objects must share a hash. The reverse isn't required.

La règle du modèle de données tient en une implication à sens unique : a == b doit entraîner hash(a) == hash(b). Rien n'oblige l'inverse — deux objets différents peuvent parfaitement partager un hash, c'est une collision, le == de secours la départage. Ce qui n'est pas négociable, c'est que deux clés considérées identiques par == atterrissent dans le même compartiment. Viole cette règle — en hachant sur autre chose que ce que compare __eq__ — et un set peut contenir un objet, recevoir son égal, et répondre que non, il n'est pas là.The data model's rule is a one-way implication: a == b must entail hash(a) == hash(b). Nothing requires the reverse — two different objects can perfectly well share a hash, that's a collision, and == breaks the tie. What's non-negotiable is that two keys considered identical by == land in the same bucket. Break that rule — by hashing on something other than what __eq__ compares — and a set can hold an object, receive its equal, and answer that no, it isn't there.

__hash__ porte sur les mêmes champs que __eq____hash__ covers the same fields as __eq__
# La règle, dans un seul sens :
# a == b  implique  hash(a) == hash(b)
#
# PAS l'inverse : hash(a) == hash(b) n'implique PAS a == b (collision, normale)

class Point:
    def __init__(self, x, y): self.x, self.y = x, y
    def __eq__(self, o):
        return isinstance(o, Point) and (self.x, self.y) == (o.x, o.y)
    def __hash__(self):
        return hash((self.x, self.y))   # basé sur les MÊMES champs que __eq__

p1, p2 = Point(1, 2), Point(1, 2)
print(p1 == p2)                 # True  — même valeur
print(hash(p1) == hash(p2))     # True  — obligatoire, sinon le set suivant ment
print(len({p1, p2}))            # 1 — un seul élément, comme prévu

__hash__ hache exactement le tuple que __eq__ compare. Deux points de même valeur : même hash, garanti — le set les traite comme un seul élément. La règle d'or : si deux champs entrent dans __eq__, ils doivent entrer dans __hash__, et rien de plus.__hash__ hashes exactly the tuple __eq__ compares. Two points of equal value: same hash, guaranteed — the set treats them as one element. The golden rule: if two fields feed __eq__, they must feed __hash__, and nothing more.

Un hash qui ment ne lève jamais d'erreur. Il rend juste l'objet introuvable, exactement là où tu l'as rangé.A lying hash never raises an error. It just makes the object unfindable, exactly where you filed it.
№ 03Le piègeThe trap5 min

Une liste n'est pas hachable — par précaution, pas par oubli.A list isn't hashable — as a precaution, not an oversight.

TypeError: unhashable type: 'list' n'est pas un manque dans la bibliothèque standard. C'est une décision : list retire volontairement __hash__ (mis à None) parce qu'elle est mutable, et qu'un objet mutable haché sur son contenu viole la règle du numéro précédent dès qu'on le modifie. Le hash calculé à l'insertion désigne un compartiment ; muter l'objet après coup ne déplace rien — il reste dans l'ancien compartiment, sous un hash qui ne correspond plus à sa valeur actuelle. Le lookup suivant, lui, recalcule le hash à partir de la valeur d'aujourd'hui et regarde ailleurs.TypeError: unhashable type: 'list' isn't a gap in the standard library. It's a decision: list deliberately drops __hash__ (sets it to None) because it's mutable, and a mutable object hashed on its content violates the previous issue's rule the moment it's modified. The hash computed at insertion designates a bucket; mutating the object afterward moves nothing — it stays in the old bucket, under a hash that no longer matches its current value. The next lookup recomputes the hash from today's value and looks elsewhere.

Python refuse avant même que le piège se refermePython refuses before the trap even closes
vus = set()
vus.add([1, 2, 3])
# TypeError: unhashable type: 'list'
# La liste n'a pas d'oubli : Python lui a explicitement retiré __hash__ (= None).

L'erreur arrive tout de suite, au moment de l'insertion — pas plus tard, quand le bug serait devenu silencieux. C'est le langage qui choisit l'échec bruyant plutôt que le lookup fantôme. tuple, lui, est hachable — mais seulement s'il ne contient que des éléments eux-mêmes hachables (un tuple de listes reste unhashable).The error fires right away, at insertion — not later, once the bug has gone silent. The language is choosing the loud failure over the ghost lookup. tuple, by contrast, is hashable — but only if it holds nothing but hashable elements itself (a tuple of lists stays unhashable).

Le contre-exemple qui rassureThe reassuring counter-example

Un objet hachable sur son id() — le comportement par défaut de toute classe — ne risque rien : son identité ne mute jamais, même si ses attributs changent. C'est pour ça qu'une instance ordinaire est hachable d'office. Le danger n'apparaît que si tu redéfinis __hash__ pour porter sur un état qui peut changer.An object hashed on its id() — the default behavior of any class — risks nothing: its identity never mutates, even if its attributes change. That's why a plain instance is hashable out of the box. The danger only shows up if you redefine __hash__ to cover state that can change.

La leçon généraleThe general lesson

Ne hache jamais sur un champ que tu comptes muter pendant que l'objet vit dans un set ou une clé de dict. Si l'objet doit muter, ne le hache pas — utilise son id() implicite, ou ne le range pas dans une structure à hash.Never hash on a field you intend to mutate while the object lives inside a set or as a dict key. If the object must mutate, don't hash it on value — rely on its implicit id(), or don't put it in a hash-based structure at all.

№ 04Le geste justeThe right move4 min

Gèle ce que tu haches, ou refuse le hash — jamais l'entre-deux.Freeze what you hash, or refuse the hash — never the in-between.

Deux réponses saines à la tension de ce numéro, et une seule mauvaise (laisser un __hash__ personnalisé porter sur un état mutable, sans discipline). La bonne réponse par défaut : rendre l'objet immuable — @dataclass(frozen=True) génère un __hash__ cohérent avec __eq__, et refuse toute mutation ultérieure, donc le hash ne peut jamais se périmer. Si l'objet doit rester mutable, la bonne réponse est l'opt-out explicite : __hash__ = None dit au langage, et à qui lit le code, que cet objet ne se range pas dans un set — pas d'erreur cachée, une TypeError immédiate et honnête.Two healthy answers to this issue's tension, and exactly one bad one (letting a custom __hash__ cover mutable state without discipline). The default good answer: make the object immutable — @dataclass(frozen=True) generates a __hash__ consistent with __eq__, and refuses any later mutation, so the hash can never go stale. If the object must stay mutable, the good answer is an explicit opt-out: __hash__ = None tells the language, and whoever reads the code, that this object doesn't belong in a set — no hidden error, an immediate and honest TypeError.

L'immuabilité rend le hash increvableImmutability makes the hash bulletproof
from dataclasses import dataclass

@dataclass(frozen=True)      # frozen=True : pas de mutation possible -> hash sûr
class Coordonnee:
    lat: float
    lon: float

vues = {Coordonnee(48.85, 2.35)}
Coordonnee(48.85, 2.35) in vues       # True — égalité et hash tiennent, à vie
c = Coordonnee(48.85, 2.35)
c.lat = 0.0                            # FrozenInstanceError — la mutation est
                                        # refusée AVANT de pouvoir casser le hash

frozen=True ne fait pas que générer __hash__ : il empêche la mutation qui le rendrait mensonger. Les deux moitiés de la solution — geler la valeur, hacher la valeur — viennent d'un seul décorateur, cohérentes par construction. C'est le premier réflexe pour tout objet destiné à devenir une clé.frozen=True doesn't just generate __hash__: it blocks the mutation that would make it a lie. Both halves of the fix — freezing the value, hashing the value — come from one decorator, consistent by construction. It's the first reflex for any object meant to become a key.

Le contre-emploiThe counter-use

Ne fige pas un objet par réflexe défensif s'il n'a jamais vocation à être une clé ou un élément de set. Beaucoup d'objets métier (une commande en cours, une connexion) sont mutables par nature et n'ont rien à faire dans une structure à hash — le laisser hachable par défaut sur id() suffit, tant qu'on ne redéfinit pas __eq__.Don't freeze an object out of defensive reflex if it was never meant to be a key or a set element. Many business objects (an in-flight order, a connection) are mutable by nature and have no business in a hash structure — leaving it hashable by default on id() is enough, as long as __eq__ stays untouched.

Le réflexe en une phraseThe reflex in one sentence

Si ton objet peut changer pendant qu'il vit dans un set ou comme clé, il n'a pas sa place là — gèle-le, ou refuse explicitement d'être haché.If your object can change while it lives in a set or as a key, it doesn't belong there — freeze it, or explicitly refuse to be hashed.

№ 05Bilan & éditoWrap-up & editorial2 min

Le protocole implicite, refermé : trois numéros, un seul principe.The implicit protocol, closed: three issues, one principle.

Trois numéros pour dire une seule chose sous trois angles : un objet Python est ce que le protocole dit qu'il est, jamais ce qu'un contrôle de type croit voir. Le №07 a montré que l'interface appartient à l'appelant, pas à une hiérarchie de classes. Le №08 a montré que la syntaxe elle-même n'est qu'une façade sur des dunders. Ce numéro a montré le prix caché de cette liberté : deux dunders qui se parlent — __eq__ et __hash__ — peuvent se désaccorder sans qu'aucune erreur ne le signale, jusqu'à ce qu'un objet devienne introuvable dans sa propre structure.Three issues to say one thing from three angles: a Python object is what the protocol says it is, never what a type check believes it sees. №07 showed the interface belongs to the caller, not to a class hierarchy. №08 showed that syntax itself is just a façade over dunders. This issue showed the hidden price of that freedom: two dunders that must agree — __eq__ and __hash__ — can fall out of sync without any error flagging it, until an object goes missing inside its own structure.

NuméroIssueCe qu'il a poséWhat it established
№ 07L'interface appartient au consommateur — isinstance ferme, duck typing ouvre.The interface belongs to the consumer — isinstance closes, duck typing opens.
№ 08La syntaxe désucre en appels de dunders, cherchés sur le type, jamais l'instance.Syntax desugars into dunder calls, looked up on the type, never the instance.
№ 09__eq__ et __hash__ forment un contrat couplé ; le rompre perd l'objet, en silence.__eq__ and __hash__ form a coupled contract; breaking it loses the object, silently.
Le protocole ne te protège jamais de toi-même. Il te donne le pouvoir, et te laisse seul avec le contrat.The protocol never protects you from yourself. It hands you the power, and leaves you alone with the contract.
Mot de l'éditeurFrom the editor

Le protocole a un axe qu'on n'a pas encore touché : le temps.The protocol has an axis we haven't touched yet: time.

Depuis le №07, chaque dunder qu'on a vu répondait à une question posée une seule fois : combien d'éléments (__len__), sont-ils égaux (__eq__), quel hash (__hash__). Une question, une réponse, instantanée. Mais Python a une deuxième famille de dunders, celle qui répond non pas une fois mais à la demande, encore et encore, jusqu'à épuisement : __iter__ et __next__. C'est le même principe du modèle de données — répondre au protocole plutôt qu'hériter d'un type — appliqué non plus à une valeur, mais à une séquence d'événements dans le temps.Since №07, every dunder we've seen answered a question asked once: how many elements (__len__), are they equal (__eq__), what hash (__hash__). One question, one answer, instant. But Python has a second family of dunders, one that answers not once but on demand, again and again, until exhaustion: __iter__ and __next__. It's the same data-model principle — answer the protocol rather than inherit a type — applied not to a value anymore, but to a sequence of events over time.

Prochain numéro : l'itérateur — __iter__, __next__, StopIteration. La différence entre un itérable (qu'on peut reparcourir) et un itérateur (qui s'épuise une seule fois) ; ce que le for désucre vraiment ; pourquoi une boucle sur un fichier déjà lu ne redonne rien. Ouverture du Vol. IV.Next issue: the iterator — __iter__, __next__, StopIteration. The difference between an iterable (re-walkable) and an iterator (exhausted once); what for really desugars into; why looping over an already-read file gives back nothing. Opening Vol. IV.