Skip to content

sentinel-lost-in-deepcopy (MUT118)

Family: Mutation & State (MUT) · Heuristic · Off by default · Severity error (a bug) · Unsafe fix (--fix --unsafe-fixes)

copy.deepcopy of an instance holding an object() sentinel in an attribute that a function tests against the sentinel by identity (the copy holds a new object, which the test does not match).

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 select or extend-select names its code or name, and with lint.heuristic = true (--heuristic) also by default and for its prefixes and ALL. It has not been measured yet. See Rule Precision.

What it does

Checks copy.deepcopy calls that copy an instance holding an object() sentinel in an attribute that a function tests against that sentinel by identity (item.default is MISSING). The copy holds a new object in the attribute, so the test gives the opposite answer on the copy.

A sentinel is a module-level name bound once to object() (MISSING = object()) that no module binds again. A class holds it in an attribute when its own code puts it there:

  • the default of a field of a stdlib @dataclass whose generated __init__ stores it (init left on, no __init__ of the class's own, and the field not declared init=False): default: object = MISSING, default: object = field(default=MISSING);
  • a store in a method: self.default = MISSING, or self.default = default of a parameter declared default=MISSING;
  • the default of a public field of a class whose base the catalog describes as keeping a hashable default as the object itself (pydantic.BaseModel), when nothing may validate the default (no validate_default in the field's annotation, and no model_config or Config in the class or a project base, which may turn it on): a validated default is what the validation returns.

The test is a comparison with is or is not in any function of the project, on an object whose class heki knows (as for MUT203). The deep copy is a call of copy.deepcopy with one argument, of an object of the class or of a subclass; the report is at that call, with the tests as related locations, so one new deep copy is one new diagnostic under a Ratchet baseline.

A deep copy also copies what the object holds in its attributes. An instance of the class held there or below, by the attributes' types (an optional attribute, the items of a list or dict, the classes implementing a protocol), is a heuristic report naming the copied object's attribute it is in or below (reference): what the attributes hold when the program runs may be other objects. A class that copies its instances itself (a copy hook, a copyreg registration) is not followed.

It does not report:

  • a sentinel that copies as itself (sentinel("MISSING"): the builtin from Python 3.15, or typing_extensions.sentinel, also through import typing_extensions as te; an instance of a class with __deepcopy__), or any other value bound to the name;
  • a sentinel only used as a parameter default or a dict.get default, never stored on an instance;
  • a class whose own code (or a base's) decides how it is copied: __deepcopy__, __reduce__, __reduce_ex__, __getstate__, __setstate__, or a copyreg registration;
  • a copy.deepcopy call given a memo (a __deepcopy__ passing its memo on);
  • comparisons with ==, and pickle, whose copy is made where it is loaded.

What a report states

A report states that the object() sentinel S is a value that class C stores in attribute a of its instances, that a function tests a against S by identity, and that copy.deepcopy receives an instance of C at the reported call: whenever the instance holds S in a, the copy holds a new object there, which the test does not match.

Its premises:

  • Object sentinel: S is a module-level name bound once to the builtin object(), which no module binds again. Established.
  • Held by the class: S is the default of a field that the __init__ a stdlib dataclass generates stores, a method of C stores S in self.a (or a parameter whose default is S), or S is the default of a public field and a base of C keeps hashable defaults as they are (R3) with nothing that may validate the default; the store runs no property, __setattr__, or metaclass of the project. Open for the default of a field under another base outside the project, or of a dataclass with an __init__ of its own, which may or may not store it.
  • Tested by identity: a function compares x.a with S by is or is not, where x is an instance of C or of a project subclass (by construction, or by annotation under R2), and reading a runs no code: no property, __getattr__, __getattribute__, or metaclass in a class it may be, and every base outside the project is object, typing.Generic, NamedTuple, or one whose __setattr__ the catalog describes as storing on the instance (R3: pydantic.BaseModel). Open when x may be of a base class of C, a union, or a protocol.
  • Deep-copied: copy.deepcopy receives, as its only argument, an instance of C (by construction, or by annotation under R2), reading a on it runs no code, and no class it may be defines __deepcopy__, __reduce__, __reduce_ex__, __getstate__, __setstate__, __getattr__, or __getattribute__, has a metaclass other than type / abc.ABCMeta, is registered with copyreg, or derives from a class outside the project other than object, typing.Generic, abc.ABC, or one whose __deepcopy__ the catalog describes as copying the attributes deeply (R3). Open when the argument may be of a subclass of its class that holds the sentinel, when it may hold such an instance below its attributes (by their types), or when a subclass, a base, or a metaclass may decide the copy.

Why is this bad?

copy.deepcopy copies every attribute of the instance, the sentinel included: an object() copies as a new object(). Code that asks whether a value was given (item.default is not MISSING) then answers yes for the copy, and treats the new object as a real value: it may write <object object at 0x...> into output, or skip a default it should apply.

Example

import copy
from dataclasses import dataclass

MISSING = object()


@dataclass
class Field:
    name: str
    default: object = MISSING


def has_default(field: Field) -> bool:
    return field.default is not MISSING


def isolated(field: Field) -> Field:
    return copy.deepcopy(field)  # `has_default(isolated(f))` is True for every field

Use instead:

MISSING = sentinel("MISSING")  # copies as itself

sentinel (PEP 661) is a builtin from Python 3.15; for an older target, import it from typing_extensions 4.16.0 or later (from typing_extensions import sentinel). The help of a report names the one the target version has. typing_extensions 4.14 and 4.15 spell it Sentinel, and copy.deepcopy of one of those raises TypeError. A sentinel's repr is its name, and pickle finds it by that name in its module, so give it the name it is bound to.

Known limitations

  • A deep copy of a container (copy.deepcopy([field])) is not followed, and an instance below the copied object's attributes is found only by their types.
  • A sentinel bound in a class body, or under another name (MISSING = UNDEFINED), is not recognized.
  • A deep copy or a test in the body of a class defined at module level (class Defaults: SPEC = copy.deepcopy(...)) is not seen; one in a class defined in a function is.

Fix safety

When the target version is Python 3.15 or later and the file of the report binds the sentinel, the report has an unsafe fix: it replaces the object() call with sentinel("NAME"), NAME being the name the sentinel is bound to, and needs no import. heki check --fix alone never applies it; --fix --unsafe-fixes does (--diff --unsafe-fixes shows it), and the language server offers it as a quick fix. It is unsafe because the object changes: its type is sentinel instead of object, its repr is NAME instead of <object object at 0x...>, and pickle of an object holding it stores the sentinel by its name and loads it as the same object, where it made a new object() before. heki assumes that the module-level name is how pickle finds it. The fix is not offered when the module binds the name sentinel (an import of unittest.mock.sentinel, a function, an assignment), or below Python 3.15.