Skip to content

write-owner-violation (MUT201)

Family: Mutation & State (MUT) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix

Writing a guarded attribute/container (directly, via alias, or via helper) outside declared write-owners.

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 when its contract is declared. It has not been measured yet. See Rule Precision.

What it does

Checks writes to attributes and containers that a [[tool.heki.write-owners]] contract reserves for a set of allowed writer functions. A write is reported when it happens outside the allowed writers:

  • directly (model.fields = [...], model.fields.append(...), del model.fields), also by calling on the attribute's value a project method that changes its own self in place, in its body, through its calls on self, or through super() (model.bag.add(x) with def add(self, name): self[name] = 1): the call changes the value as a builtin container's changing method does, whether or not the contract allows the method itself. A method that only reads its self, or changes only an object it builds, writes nothing;
  • through a local alias (fields = model.fields; fields.append(...)), also one a scope nested in the function reads from it (a nested function, a lambda, a comprehension, or a generator expression: lambda: fields.append(x)) unless a nested scope rebinds it (nonlocal), one getattr with a constant name loads (getattr(model, "fields").append(...)), or what a method, property, or function returns when it returns the attribute itself on every return (model.field_list().append(...) with return self.fields), stores no attribute of that name itself, and every class the object may be runs it (no cached_property, no class attribute of the name coming first); the object must be passed by position (no keyword-only parameter, no *args unpacking);
  • through setattr(model, "fields", ...) / object.__setattr__ (also through a module-level name bound once to it: _set = object.__setattr__) or model.__dict__["fields"] (also vars(model)["fields"], model.__dict__.setdefault("fields", v), and a local alias of the namespace), also with a string constant for the name (model.__dict__[FIELDS_KEY], imported or not): a module-level name declared Final or bound once in its module and rebound by no other (a module __getattr__ caching what it serves, globals()[name] = value, leaves the names the module body binds on every path, since Python calls it only for a missing name, unless a decorator wraps it or another module loads it), or a class-body name declared ClassVar or Final and bound once (self.KEY, cls.KEY, Model.KEY), which every subclass of the object's class finds along its MRO in the same class (none defines it again or lists another base defining it first, class Child(Other, Model)) and no code stores on the class, a subclass, or an instance (Model.KEY = "x"; another module may store it on the defining class only for a Final one); on an instance of a protocol, every class implementing it must hold the same constant. A Final name of a dataclass (or of a class a dataclass_transform builds) is a field, which each instance holds itself (Keys("x").KEY): it names an attribute only when read on the class object of a dataclass whose default no class along the way replaces (one with slots=True or built by a transform); a name a loop takes from a tuple, list, or set of such constants (for key in ("fields", FIELDS_KEY): setattr(model, key, [])), or from a module's tuple of them (for key in RECORDS, imported or not), writes each of them, when no code changes the list or set (keys.append(name) makes the name unknown), and so does the key of each pair a generator gives __dict__.update (copy.__dict__.update((key, src.__dict__[key]) for key in RECORDS));
  • into the entries of the container the attribute holds (model.meta["kw"][name] = v, model.meta["kw"].append(v), through a local alias of the entry): an item_mut write;
  • through a helper that mutates the container or object it receives (helper(model.fields)), reported once at the outermost call site. A helper that sees the object's class (an annotated parameter, self of a method) reports its own write instead, so a write it routes through the allowed writers stays allowed for its callers; a helper handed the value of an attribute (helper(field.data_type)) writes that attribute only when it changes the value in place, and otherwise writes the value's own attributes. A helper that does not see the class and only hands the value on to an allowed writer or an exempt method writes inside the owner.

A target names a class and an attribute; it covers the class's subclasses too (the target's class family). With unlisted-dict-keys = "report", a constant key written through the namespace of an object of a class a target covers (field.__dict__["_cache"] = v, vars(field).setdefault(KEY, v), del field.__dict__[KEY]) is reported too when no target covering that class names it, in this contract or in any other write-owners contract (writespkg.model.Field._cache(as adictitem), adictkey no target names), so a new key needs a target first. A target names the keys its attribute pattern matches, and an entry target names its container; a key another contract names is judged by that contract alone, a contract with only forbidden-writers allows no writer and names no key, and a contract allowing every writer (allowed-writers = ["*"]) lists keys any function may write. A computed key, a plain attribute store (field._cache = v, setattr), and a write in a helper that does not see the object's class are not such writes. A target can also name one entry of the container an attribute holds, Class.attr["key"]: it matches the writes of that key (field.extras["init"] = v, field.extras[INIT] with a string constant, field.extras.pop("init"), del field.extras["init"], field.extras["init"].append(v), and a store operation called with the key, set_extra(field, "init", v) writing field.extras[key], reported at the call), not a write of the whole container (field.extras = {}, field.extras.update(...)) or with a computed key, which are writes of Class.attr. When a contract names both a container and one of its entries, a write of the entry is reported once, under the entry.

The written object's class is the one heki infers for it, with annotations as hints: a parameter, local, attribute, or return annotation, including the items of list[...], Sequence[...], Iterable[...], Iterator[...], Generator[...], dict[...], Mapping[...], tuple[...], and set[...], and a type alias naming one (Models: TypeAlias = list[Model]); a constructor call; and what the object comes from: a loop over such a container (for model in models), a subscript (models[0], by_name["a"]), unpacking (model, _ = pair), dict views and get / pop, enumerate, zip, reversed, sorted, iter, next, list / tuple / set, itertools.chain, a display, the items appended to a local list, or a comprehension or generator expression. A method call or a @property / cached_property read has the return annotation of the definition the receiver's class finds first along its MRO, as for a type checker (typing.Self is the receiver's class); a copy (copy.copy, copy.deepcopy, dataclasses.replace, model_copy) has its original's class, calling a functools.partial object returns what the wrapped function returns, and typing.cast names the class of its value, its type read as an annotation (cast(list[Model], x) as cast("list[Model]", x)): a cast to a subclass narrows a value known as its base, and a cast to Any or to a base class keeps the class the value is known to have, as an annotated local does. A cast hands back the object it is given, and so does a project function returning its parameter on every path (def same(x): return x, also return cast(T, x)): cast(list[int], store.items).append(x) and same(store.items).append(x) change store.items, as an alias does. A variable rebound in a loop (node = node.parent) or assigned on some paths only (a walrus inside and / or) has the classes of the values reaching it; a value of two or three classes (Model | Node, from an annotation or from different assignments) is each of them, and an isinstance check narrows it in the code it guards (if isinstance(x, Model): ..., if not isinstance(x, Model): return, also inside and / or). A value typed with a project Protocol is an instance of the protocol and of the project classes that implement it structurally (having every member it defines; at most eight, counting a class and not its subclasses), also when it is handed to a helper that does not type it: a target on the protocol and one on an implementation both cover its writes. An object whose class heki cannot see (an unannotated parameter or return, Any, a value of more than three classes, a protocol without members or with more implementations) is not tied to the target.

A private helper (_name, or a comprehension, generator expression, or lambda scope) with project callers hands the responsibility to its callers: the write is reported at the call sites of the first non-private callers, with the chain of calls as related information. A private function that only its own recursion calls (_walk calling itself, handed out as a callback) has no such caller and reports its writes itself. One report stands for every write behind that call (sites in JSON), so a Ratchet baseline counts a second write inside a recorded helper. A write matching several targets of one contract (A.items and E.items for a write on an E, a subclass of A) is one report, under the target configured first, naming the others ((alsoE.items)). A write reached through an allowed writer on one path and around it on another (or through a forbidden writer on one path only) is reported for the path the contract does not allow. Reading a @property or functools.cached_property attribute calls its getter, so a private getter hands its writes to the functions reading it; a read never calls a property's setter.

A write runs where the body holding it runs. Calling a generator function only creates the generator: its writes run where it is iterated (as for EFF101), so a generator created by an allowed writer and iterated elsewhere writes elsewhere, and one handed to an allowed writer that iterates it writes inside the owner. A generator that is created and never iterated writes nothing. A coroutine that is never awaited or driven at a project call (handed to asyncio.create_task, ensure_future, gather, ...) runs on the event loop: a private one reports its own writes instead of handing them to the function that created it. Functions run on another thread by an offloading decorator (@sync_to_async, ...) are not followed either.

A function that only runs inside the owner's operations is not reported either: it has project callers, and every path of callers above it starts in an allowed writer, an exempt method, or the class's own initialization (a mutator method that only the store and __init__ call). A function without project callers, one that is also called from anywhere else, or one reached only through a cycle of other functions stays reported.

With attribution = "lexical", neither of the two rules above applies: a write is judged in the function whose code holds it, whoever calls that function. The write statement is its function's own, and so is a call handing a typed object to a helper that changes it without knowing its class (fill(model.fields), reported with via the helper, which never sees the class); a write a callee makes is reported at that callee. A lambda, comprehension, or generator expression is part of the function it is written in, and a nested def is a function of its own. A class's own initialization and fresh-objects still allow a write, the initialization through the helpers it passes self to included: a helper whose every path of project callers starts in an initializer handing it its own self.

With own-receiver = "allow", a write through the receiver of the method it is judged in is allowed: the function reported (with attribution = "lexical", the function holding the write) is a method that is no static method, and the object the member is looked up on may be its first parameter (self._cache[k] = v, setattr(self, name, v)), also for a member the class inherits. Another parameter, an attribute of the receiver, and a nested def, lambda, or comprehension using the enclosing method's self stay reported.

With allowed-protocols, a write through a value typed with a project protocol the key names that declares the attribute (parser._flag = True with parser: RenderHost, RenderHost inheriting the declaration from a base protocol) is allowed, wherever it is judged; a write through another protocol, the implementation's class, or a value a helper changes without typing it stays reported. A pattern names the subprotocols of the protocols it matches too, unless protocol-subclasses = false.

A class's own initialization is allowed: a write inside an initializer (__init__, __post_init__, __new__, model_post_init, __setstate__) of a class of the target's family is not reported when the written object is the initializer's own self, whether it writes it directly, through a local alias, through super().__init__(), or through helpers it passes self to (self._init_fields(), _setup(self)). An object that may be self (self if flag else other) gets the benefit of the doubt. Writes to objects that are provably not self stay reported: another parameter, an attribute of self.

A write that constructs the object it writes is allowed too (fresh-objects = "allow", the default): the object was allocated in the same call chain, by calling its class, by object.__new__(Model) (also Model.__new__(Model) when no class defines __new__), by copying (copy.copy, copy.deepcopy, dataclasses.replace, .copy(), .model_copy()), or by a project function that returns such an object (at a call leaving an optional parameter at a default without elements, such as None, the paths returning an element of it return nothing) or returns the one it is handed, and nothing else can hold it yet: no store into another object, a container, a global, or a closure, no yield, and no call that may keep it ran before the write. A project function keeps an object it stores, yields, or hands to code heki does not follow or to a function that keeps it; reading or writing it keeps nothing. A store made only where tests of the function's parameters pass (if register:) keeps nothing at a call whose arguments fail them (register=False, or a default the call leaves). Writes that a helper makes to a new object its caller hands it count as well. A shallow copy shares its containers with the original, so only rebinding its attributes constructs it (copied.data_types = [...]); copied.data_types.append(x) changes the original's list and is reported. fresh-objects = "report" reports these writes like any other.

The help starts with the contract's message and then names up to three allowed writers that write the member the report names themselves: public functions and methods an allowed-writers pattern names (with forbidden-writers, every function outside them), by fully qualified name (allowed writers of `Model.fields`: `pkg.store.Store.add_field`). A write through a helper, a write that constructs the object it writes (with fresh-objects = "allow"), private functions (_name), special methods (__init__), and the exempt methods do not count. JSON output gives them with their files as allowed_examples (fqn, path); a report without one has no such field.

What a report states

A report states that the function writes a target of a write-owners contract (an attribute, or the container it holds) outside the contract's write owners, directly, through an alias, or through the helpers shown; with unlisted-dict-keys = "report", also that it writes a __dict__ key of a target's class that no write-owners target names.

Its premises:

  • Target: the object is an instance of a class the contract names, or of a subclass, by construction or annotation (assumption R2), and the attribute is a target's (with unlisted-dict-keys = "report", or a __dict__ key no write-owners target names). Open: an alias bound on one path is enough.
  • Outside the owners: the function is not in the allowed modules and classes, nor runs only inside allowed contexts (with attribution = "lexical": the function holding the write is not allowed, nor runs only inside a class's own initialization; with own-receiver = "allow", the written object is not the receiver of the method judging it). Established from the contract.
  • Through helpers: a helper's write, read, or call counts at its caller (with attribution = "lexical": only a helper changing a typed object it is handed without knowing its class). Open: one path of the helper is enough.
  • Changed by its method: a project method called on the attribute's value changes its own self in place. Open: one path of the method is enough.

Why is this bad?

Large code bases often have one component that owns a piece of shared state (a store, a registry, a cache). Writes from anywhere else bypass its invariants and make bugs that depend on call order. The contract states the ownership once in configuration, with no runtime cost and no decorators.

Example

[[tool.heki.write-owners]]
name = "model-store"
targets = ["Model.fields"]
allowed-writers = ["Store.*"]
exempt-methods = ["__deepcopy__"]
message = "use Store.add_field() instead"
class Model:
    def __init__(self) -> None:
        self.fields: list[str] = []  # allowed: the class's own initialization

    def __deepcopy__(self, memo: dict) -> "Model":
        new = Model()
        new.fields = list(self.fields)  # allowed: exempt method
        return new


class Store:
    def add_field(self, model: Model, name: str) -> None:
        model.fields.append(name)  # allowed writer


def parse(model: Model) -> None:
    model.fields.append("id")  # MUT201: outside `Store.*`

Use instead:

def parse(model: Model, store: Store) -> None:
    store.add_field(model, "id")

Fix safety

No automatic fix.

Options

  • [[tool.heki.write-owners]]:
  • name: the contract name, shown in messages.
  • targets: Class.attr entries; globs and dotted suffixes match (Model.fields, pkg.model.Model.*).
  • allowed-writers: functions allowed to write the targets, as dotted names or globs matched against the function's qualified name and its Class.method qualname (Store.*, pkg.parser.generation.*). A module part names one module without its submodules: pkg.model:* allows what pkg/model/__init__.py defines, not pkg.model.io.save.
  • forbidden-writers: when set, only writes by these functions are reported (matched like allowed-writers, pkg.render.*); allowed-writers and exempt-methods stay exceptions inside them. A write is in scope when a function on its chain (the reporting function, the private helpers it hands the write through, or the writer) is forbidden.
  • exempt-methods: construction and copy methods allowed to write the targets. A plain name (__deepcopy__, copy_deep) matches any function or method of that name; an entry with a dot or a glob (Model.copy_deep, create_*) is matched like allowed-writers. A write is allowed when any function on its chain (the writer and the private helpers between) is an allowed writer or an exempt method.
  • message: the help of every report of the contract (use Store.add_field() instead).
  • forbid-cached-property-on: classes on which a @cached_property is itself reported.
  • fresh-objects: "allow" (default) or "report": whether writes that construct the object they write are reported.
  • unresolved: "ignore" (default) or "report": also report the writes the contract cannot tie to a class, under MUT205. A function some code hands on as a value (a display, a class attribute, an argument, a return: HANDLERS = [helper], REQUIRE = staticmethod(helper)) has callers heki does not see: with "report", it judges its writes itself, as if it had no callers.
  • attribution: "call-graph" (default) or "lexical": whether a private helper hands its writes to its callers and a function that only runs inside allowed writers is allowed, or each write is judged in the function holding it.
  • own-receiver: "report" (default) or "allow": whether a write through the receiver of the method it is judged in (self, cls, super()) is allowed.
  • allowed-protocols: project protocols (class patterns, their subclasses included): a write through a value typed with one that declares the attribute, itself or through its protocol bases, is allowed, for the protocol's member and each implementation's attribute alike.
  • protocol-subclasses: true (default) or false: whether an allowed-protocols pattern names the subprotocols of the protocols it matches, or those protocols only.
  • unlisted-dict-keys: "ignore" (default) or "report": also report a constant __dict__ key of a target's class that no target of any write-owners contract names.