1.1 KiB
nil_sentinel_pattern — v1
Why this iteration: Lifted verbatim from conductor/code_styleguides/error_handling.md §"The 5 Patterns" #1 (lines 23-47).
This is the baseline encoding — the convention-style description with code example currently in production.
Future variants will test alternative encodings (rationale-first, before/after, tabular) against this baseline.
Source: conductor/code_styleguides/error_handling.md:23-47
1. Nil-Sentinel Dataclasses (replaces None)
When a function would "return None" in conventional Python, return a nil-sentinel dataclass instead. The sentinel has all default values (zero-initialized) and is safe to read from.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class NilPath:
exists: bool = False
read_text: str = ""
errors: list[ErrorInfo] = field(default_factory=list)
NIL_PATH = NilPath() # module-level singleton
Callers don't need if x is None: checks; they can call x.read_text and
get "" on the nil path.
Convention: NIL_* (uppercase) is the module-level singleton. Nil*
(PascalCase) is the class. Frozen dataclass prevents runtime mutation.