hash-attr-mutation (MUT107)¶
Family: Mutation & State (MUT) · Heuristic · Opt-in · Severity error (a bug) · No automatic fix
Opt-in: a method other than the initializers rebinds or changes in place an attribute that the __hash__ of its instances reads.
Heuristic
This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. Of 50 sampled reports (round 3, 2026-11-21), 78% were right about the code. See Rule Precision.
What it does¶
Checks methods that rebind or mutate an attribute that the __hash__ of their instances reads
(directly, through a self.helper() call, or through the getter of a property it reads, such as
hash(self.key) where the @property key reads self.name), when the class, one of its
subclasses, or a base-class method it inherits without overriding changes the attribute after
initialization. Each self call in the hash runs the definition the writer's class finds along
its MRO, not an override in another subclass. A property that also defines a setter or deleter
is not followed. The rule is opt-in: it runs when select or extend-select names it.
The rule reports the write itself, once per method and attribute. It does not report:
- initialization:
__new__,__init__,__post_init__,model_post_init,__setstate__,__enter__,setup,setup_*/_setup_*/_init_*/_configure_*methods, and the private helpers they call (self.__setstate(state)on the instance__new__allocates included), and the private helpers that only__init__and such helpers call onself(__init__->self._load()->self._decode()); class attributes that__init_subclass__sets; - writers whose instances use another hash: a class between the writer's class and the hash's
defines its own
__hash__, or__eq__without__hash__(Python then makes its instances unhashable); - in-place changes (an item store, a mutator method such as
append) of an attribute__hash__hands whole tohash()(hash(self.items),hash((self.kind, self.items))) and reads for nothing else: the hash is the value's own, so a list, dict, set, orbytearraythere cannot be hashed at all, and a value of a project class answers for its own hash (MUT107checks its class). Rebinding the attribute is reported; - classes with a metaclass other than
type/abc.ABCMetaalong their MRO (also one heki cannot resolve), and classes with a base heki names no class for (with_metaclass(Meta), a module variable such asBase = declarative_base()), whose metaclass is unknown: the metaclass may turn attribute writes into descriptor calls (a generated property whose setter invalidates the cached value), which heki does not see; - writes that are no plain store: an attribute that a class along the MRO binds to a property
(
@property,@x.setter,@x.deleter,x = property(...)), whose setter or deleter runs instead, or which raises without one, and any write on a class whose MRO defines__setattr__or__delattr__; - lazy initialization: a write under a
None/ falsy check of the same attribute (if self._key is None: self._key = ...,if not self._parts: ..., also ofgetattr(self, "_key", None)andhasattr(self, "_key")), or in theexcept AttributeError:clause of atrythat reads it; - memo / cache dictionaries (
self._cache[key] = value,setdefault, theif key not in self._memo:pattern): in-place changes of an attribute with acacheormemoword in its name; rebinding it (self.cache_size = n) and names such asmemory_limitare no memo operation; - constant dictionary keys
__hash__never reads (self.meta["note"]while__hash__readsself.meta["id"]); - the hash's own cache: an attribute the hash computation writes itself (
self._hash = ...in__hash__or aself.helper()it calls), which other methods reset, and a stored hash value (self._hash,self._hashcode) that a deserialization hook recomputes.
What a report states¶
A report states that a method other than the initializers rebinds or changes in place, with a
plain store, an attribute that the __hash__ of its instances reads.
Its premises:
- Hash reads: the
__hash__the writer's class finds along its MRO reads the attribute, directly, through aselfmethod, or through a property getter, each the definition that class finds along its MRO. Open: aselfcall heki does not resolve is not followed. - Outside initialization: the method is not an initializer. Open: initializers are recognized by their names and by who calls them (listed above).
- Plain store: the method stores to the attribute, deletes it, or changes it in place, and no
class along the MRO turns the write into a call (a property,
__setattr__,__delattr__, a metaclass other thantype). Open: a base outside the project can define any of them.
Not part of the claim: that an instance is in a set or dict when the write runs. That is the harm: the set or dict files the instance under its old hash.
Why is this bad?¶
A set or a dict files an object under the hash it had when it was added. Once an attribute
the hash is computed from changes, lookups compute a different hash and look in the wrong
place: obj in seen is False for an object that is in seen, a dict holds a key no
lookup finds, and the object can be added a second time.
Example¶
class Tag:
def __init__(self, name: str) -> None:
self.name = name
def __eq__(self, other: object) -> bool:
return isinstance(other, Tag) and other.name == self.name
def __hash__(self) -> int:
return hash(self.name)
def rename(self, name: str) -> None:
self.name = name # a `Tag` already in a set is filed under its old hash
Use instead:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Tag:
name: str
def rename(tag: Tag, name: str) -> Tag:
return replace(tag, name=name) # a new object, hashed when it is stored
Fix safety¶
No automatic fix: whether to make the object immutable, hash only fields that never change, or remove the object from its containers before changing it is a design decision.