/python-tooling:python-slots-mock-patch-objectfrom python-tooling
Fix for `AttributeError: '<ClassName>' object attribute '<method>' is read-only` raised during `mock.patch.object()` teardown. Use when: (1) a Python test using `unittest.mock.patch.object(instance, "method")` passes the patched code but raises an AttributeError during context-exit (visible in the stack as `mock.py:1635` calling `delattr(self.target, self.attribute)`); (2) the target class declares `__slots__`; (3) the test was working before someone added `__slots__` to a base class or the target class itself; (4) a refactor introduced `__slots__` "for efficiency" and broke a previously-green test suite. Covers root cause (`__slots__` blocks `delattr` because it doesn't allocate `__dict__`, so the attribute can't be removed after the patch sets it), the diagnostic signature, the canonical fix (drop `__slots__` if the class is a mock target), and when `__slots__` IS the right call (when memory matters AND the class is never patched).
Ships in python-tooling. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
__slots__ + mock.patch.object Incompatibilitymock.patch.object(target, attribute) works in two phases:
setattr(target, attribute, mock_object) — replaces the
attribute with a MagicMock for the duration of the patch context.delattr(target, attribute) (or setattr of original)
— removes the patch when the context exits.If the target's class declares __slots__, the teardown's delattr
fails:
AttributeError: '<ClassName>' object attribute '<method>' is read-only
Stack trace points at mock.py:1635 in _patch.__exit__:
delattr(self.target, self.attribute)
Root cause: __slots__ doesn't allocate __dict__ for instances. Each
slot is a fixed descriptor, not a dynamically removable attribute.
Setting via setattr works (replaces the slot's value), but deletion
fails because the slot itself is part of the class definition, not the
instance's free attribute storage.
The setup phase works without warning, so the regression often only surfaces during cleanup — which is after the test's actual assertion has run. The test "passes" mid-flight and fails on teardown, making the error look like infrastructure noise rather than a real bug.
Look for this exact pattern:
unittest.mock.patch.object(instance, "method_name"),
either as a context manager, decorator, or mock.patch.object(...).start().__slots__ = ("...",) declared.'<ClassName>' object attribute '<method>' is read-only.mock.py:_patch.__exit__ →
delattr(self.target, ...).__slots__ (or moved the
class into a hierarchy where a base class has __slots__).__slots__For the vast majority of cases, the class shouldn't have __slots__
in the first place if it's a mock target. Memory savings of
__slots__ are real but small (~80 bytes per instance vs. __dict__
overhead) and only matter at scale (millions of instances).
# Before
class _ConfigBuilder:
__slots__ = ("_fn",)
def __init__(self, fn): self._fn = fn
def build(self, args): return self._fn(args)
# After
class _ConfigBuilder:
# NOTE: deliberately no __slots__ — these instances are targets of
# mock.patch.object(builder, "build") in tests/.../test_*.py, and
# __slots__ blocks the delattr that mock teardown does. Memory
# savings of __slots__ are negligible at the ~N instances we have.
def __init__(self, fn): self._fn = fn
def build(self, args): return self._fn(args)
The inline NOTE is important — without it, a future refactor will
re-add __slots__ and re-break the tests.
__slots__ IS the right callKeep __slots__ if all three apply:
__dict__ overhead is meaningful.If conditions 1+2 hold but 3 doesn't, refactor the test to mock
something other than the class itself — e.g. mock a function the class
calls, or mock the class's CONSTRUCTOR (not an instance method) so the
patch operates on the class object (which has __dict__) rather than
the instance (which has only slots).
If __slots__ truly must stay:
# Don't do this — __slots__ will fight you on teardown:
with mock.patch.object(builder_instance, "build") as mock_build:
...
# Do this instead — patch the underlying function:
with mock.patch.object(builder_instance, "_fn") as mock_fn:
...
# Or patch at the class level (class object has __dict__):
with mock.patch.object(_ConfigBuilder, "build") as mock_build:
...
Trade-off: class-level patching affects ALL instances, which may break
other tests in the same file. Patching _fn (an internal) couples the
test to the class's private structure.
After applying the fix:
__slots__
baseline.mock.patch.object(instance, "method") is in the test code
that was failing (not mock.patch.object(SomeClass, "method") which
patches at the class level — that works fine with __slots__).The setup:
PR #51 (refactor(specs): collapse Protocol + builder classes) introduced
_ConfigBuilder as a callable wrapper to share builder logic across
multiple STRATEGY_SPEC.builder= references. The agent author added
__slots__ = ("_fn",) as a "Pythonic" choice for an instance with one
attribute.
The bug:
Two pre-existing tests:
# tests/backtest/test_strategy_runner.py
def test_actor_builder_called_before_strategy_builder():
spec = STRATEGY_SPECS["kronos"]
with mock.patch.object(spec.builder, "build") as mock_build:
run_strategy(spec)
mock_build.assert_called_once_with(...)
# AttributeError raised HERE on context exit, after assertion passed
These tests had been green for months. PR #51's __slots__ addition
silently broke them. The agent's pre-merge verify said "477 passed,
0 failed" — but in fact a subset of tests had been excluded from that
run, and the regression only surfaced when the next merged-into-main
branch picked it up.
The fix:
Single line removed from _ConfigBuilder:
# class _ConfigBuilder:
# __slots__ = ("_fn",) # ← removed; added comment explaining why
477/0/1 restored. Total time: ~5 minutes once the diagnosis was clear.
Diagnostic clue we missed for ~30 minutes (only because the simplify
loop's verify step caught it): the AttributeError signature
"'X' object attribute 'Y' is read-only" with Y being a method name.
For a slot, that signature reads naturally, but it's the SAME signature
as for a @property with no setter — so the first guess is "did
someone make build a read-only property?" That's the wrong tree. The
right one: check if the class has __slots__.
__slots__ (Python 3.10+ supports
@dataclass(frozen=True, slots=True)) hit the same trap. The trip
wire is the same: delattr blocked by slots.__slots__ internally. If you mock
methods on Pydantic models, you'll hit this. Workaround: mock the
Pydantic class's METHOD at the class level, not the instance.__slots__-like behavior. If you can't mock.patch.object a method
on a Cython-backed class, this is why.__slots__ saves memory but blocks reflection. Two costs of the
same trade-off. Mock-based tests are reflection.__slots__
— see "Notes on using slots" section: "Without a dict
variable, instances cannot have new variables not listed in the
slots definition."unittest.mock.patch.objectWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub cajias/claude-skills --plugin python-tooling5 skills in this plugin
/importlib-reload-class-identityDiagnose and fix the silent class-identity drift caused by `importlib.reload()`
on modules that define classes whose instances live elsewhere. Use when:
(1) a pytest fixture uses `importlib.reload(some_module)` to "flush caches"
and downstream tests then fail with `isinstance` checks rejecting objects
that LOOK correct; (2) you see a diagnostic warning of the form "expected X,
got X" — same class name, different class identity (`type(obj).__name__ ==
"X"` but `obj is not isinstance(X)`); (3) one fragile test fixture causes
dozens-to-hundreds of cascading failures in unrelated test files; (4) tests
pass in isolation but fail when run as part of the full suite, with order
dependence pointing at the reload site; (5) you have an entry-point /
plugin / discovery system whose post-reload registry is empty even though
the underlying entries still exist. Covers root cause (Python class objects
are first-class identities; reload mints new ones; pre-reload instances
keep old identity), the diagnostic signature, and the canonical fix
(subprocess isolation via `subprocess.run([sys.executable, "-c", ...])`
or `pytest-forked` — never `importlib.reload` for class-exposing modules).
/kronos-pypi-collisionFix for `pip install kronos` returning the wrong package when trying to use
the financial K-line foundation model. Use when: (1) you intend to use the
Kronos OHLCV/K-line transformer from arXiv 2508.02739 (Shi et al., AAAI 2026),
(2) `pip install kronos` succeeds but `import kronos` fails with
`ModuleNotFoundError: No module named 'django'` (the unrelated PyPI package
is a Django-based scheduler), (3) you can't find a `kronos` pip package that
exposes `Kronos`/`KronosTokenizer`/`KronosPredictor`. The financial Kronos
model has no published pip package under that name; install from the GitHub
repo (`shiyu-coder/Kronos`) instead. Also covers Mac (Apple Silicon) usage:
device must be `"cpu"` or `"mps"`, never `"cuda:0"`.
/ruff-jupyter-diff-inflationPrevent or diagnose massive PR diffs (700-1000+ lines per .ipynb) when
running `ruff check --fix` or `make lint-fix` in a Python project that
checks in Jupyter notebooks. Use when: (1) a lint cleanup PR explodes
from a small expected diff to thousands of lines; (2) `git diff` of a
notebook shows `source` field changing from a single string to an array
of lines (or vice versa); (3) deciding how to scope ruff in a project
with both .py files and committed notebooks. Covers the structural
Jupyter source-format normalization that ruff performs and the
pyproject.toml change to suppress it.
/uv-worktree-venv-fallthroughFix for phantom Python test failures in fresh git worktrees of
uv-managed projects, caused by `uv run` falling through to a
PATH-resolved command (e.g. homebrew Python 3.9's pytest) when the
worktree's `.venv` doesn't have the command installed. Use when:
(1) `uv run pytest --collect-only -q` in a freshly-created worktree
reports `ModuleNotFoundError: No module named 'msgspec'` (or any
other project runtime dep) on test files that import the package;
(2) you see `ImportError: cannot import name 'UTC' from 'datetime'`
or `dataclass() got an unexpected keyword argument 'slots'` despite
`pyproject.toml` requiring Python 3.10+/3.12+;
(3) the same `uv run pytest` succeeds on the main worktree but fails
on a sibling worktree;
(4) `which pytest` (or `which ruff`, `which mypy`) inside the
worktree resolves to `/opt/homebrew/bin/...` instead of
`<worktree>/.venv/bin/...`;
(5) you're orchestrating parallel agents in worktree-isolation mode
and they report wildly inconsistent test results vs the main tree.
Root cause is `uv run`'s fallthrough to `$PATH` when the venv doesn't
have the command, combined with empty `.venv` in fresh worktrees.
Fix is one command: `uv sync --extra dev`.