/python-tooling:importlib-reload-class-identityfrom python-tooling
Diagnose 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).
Trending skills
7-day visitors to each skill page
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.
importlib.reload(some_module) recreates everything in some_module — including
the class objects defined there. The new class is a different Python object from
the original, even though it has the same __name__, __qualname__, and
identical fields. Any instance created before the reload retains a reference
to the old class. After the reload:
import some_module
old_instance = some_module.SomeClass(value=1)
import importlib
importlib.reload(some_module)
isinstance(old_instance, some_module.SomeClass) # False ← THE BUG
type(old_instance).__name__ == some_module.SomeClass.__name__ # True ← MISLEADING
type(old_instance) is some_module.SomeClass # False
This is the same well-known footgun behind "isinstance lies after reload" (see PEP 489 motivation), but it bites hardest in plugin / entry-point discovery systems that:
StrategySpec, Plugin, Resource) in module A.MY_PLUGIN = SomeClass(...).isinstance(loaded_obj, SomeClass) to validate the
discovered object.If anything later calls importlib.reload(module_A), the discovery code sees
the new SomeClass, but the constants in the strategy modules still hold
the old class. The defensive isinstance check rejects every entry, and
the registry ends up empty — usually with a diagnostic warning that's
maddeningly unhelpful: "expected SomeClass, got SomeClass".
You are likely hitting this bug if any of the following:
A pytest fixture flushes caches via something like
importlib.reload(specs_module)
importlib.reload(strategies_module)
importlib.reload(cli_module)
and post-fixture tests start failing.
Tests pass in isolation (pytest path/to/test.py::test_x) but fail in the
full suite — order-dependent breakage points at one reload site.
A discovery / entry-point / registry function returns empty data after
some test runs, even though the entries are still installed and visible
via importlib.metadata.entry_points() or equivalent.
You see warnings like expected StrategySpec, got StrategySpec /
expected Plugin, got Plugin in test logs — same name, different class.
A single broken test fixture cascades into dozens or hundreds of failures across unrelated test files.
You diagnose with print(id(type(obj)), id(SomeClass)) and they differ
while names match.
Don't reload the module. Use subprocess isolation instead.
importlib.reload is fundamentally fragile for any module that defines a
class whose instances exist elsewhere. The fix isn't to make reload smarter
— it's to give each invalidation-needing test its own Python process.
Best for small assertions. Each invocation gets a fresh import graph:
import subprocess
import sys
def test_external_plugin_is_discovered(installed_plugin: None) -> None:
result = subprocess.run(
[
sys.executable,
"-c",
"from my_pkg.discovery import REGISTRY; "
"assert 'my_external' in REGISTRY, sorted(REGISTRY)",
],
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, (
f"subprocess assertion failed:\n"
f"stdout:\n{result.stdout}\n"
f"stderr:\n{result.stderr}"
)
Best for whole tests that need isolation. Add to pyproject.toml:
[project.optional-dependencies]
dev = ["pytest-forked", ...]
Then mark tests:
@pytest.mark.forked # each test runs in its own subprocess
def test_plugin_discovery():
...
Best for entire test files that need isolation. Add --forked or
--dist=loadfile to pyproject.toml's addopts. Run-time cost: minimal
for small test counts.
Tempting but a trap. To make reload work, you'd need to evict every module that:
This list is unbounded and grows whenever new code touches the registry. Subprocess isolation has none of these failure modes.
After applying the fix:
Run the previously-failing tests in isolation — they should still pass.
Run the full suite — pre-existing cascading failures should collapse to zero.
Search the codebase for other importlib.reload calls in test code:
grep -rn "importlib.reload\|reload(" tests/ --include="*.py"
Audit each one. If the reloaded module exports a class whose instances live elsewhere, fix it the same way.
Setup:
nautilus_trading.cli._strategy_specs defines class StrategySpec.strategies/{forex,crypto}/ each export
STRATEGY_SPEC = StrategySpec(...) — instances created at the strategies'
import time.nautilus_trading.strategies lets external packages
contribute strategies the same way._discover_strategy_specs() at module load time iterates entry-points,
calls ep.load(), validates isinstance(spec, StrategySpec), builds a
registry dict.The bug:
importlib.reload(nautilus_trading.cli._strategy_specs) to "flush the
registry cache" so the freshly-installed external strategy would be
discovered.StrategySpec class identity. The 9 in-repo
strategies' STRATEGY_SPEC constants kept the old class identity (their
modules were not reloaded).isinstance(spec_obj, StrategySpec) check
rejected the in-repo specs with the diagnostic warning
"expected StrategySpec, got StrategySpec".Diagnostic clue we missed for ~10 minutes:
The warning message "expected StrategySpec, got StrategySpec" — same name, different class — is the loud tell. If you see "expected X, got X" anywhere in your logs, suspect class-identity drift before suspecting anything else.
The fix:
Rewrote the smoke fixture to invoke its assertions in a fresh subprocess:
@pytest.fixture(scope="module")
def installed_external_strategy() -> Iterator[None]:
uv = _uv_or_skip()
subprocess.run(
[uv, "pip", "install", "--editable", str(FIXTURE_DIR), "--quiet"],
check=True,
)
try:
yield
finally:
subprocess.run(
[uv, "pip", "uninstall", FIXTURE_DIST_NAME, "--quiet"],
check=True,
)
def test_external_strategy_is_discovered(installed_external_strategy: None) -> None:
result = subprocess.run(
[sys.executable, "-c",
"from nautilus_trading.cli._strategy_specs import STRATEGY_SPECS; "
"assert 'external_strat' in STRATEGY_SPECS"],
capture_output=True, text=True, check=False,
)
assert result.returncode == 0, f"{result.stdout}\n{result.stderr}"
The reload chain (_flush_strategy_caches) was deleted entirely. The
sys.path shim and _drop_external_strat_from_sys_modules helper went with
it — they were also workarounds for the in-process reload approach.
Outcome: 73 → 0 cascading failures, lint clean, single-commit fix.
__eq__ is
field-based but isinstance is identity-based — old and new instances
compare as equal but fail isinstance checks.issubclass() checks, exception-class catching,
Pydantic / msgspec validators, and anything else that compares class
identity.importlib.reload
docs:
"As with all other objects in Python the old objects are only reclaimed
after their reference counts drop to zero." But the practical
consequences for isinstance are not spelled out.isinstance against post-reload classes for any
pre-reload instance. Either re-create those instances after reload, or
use duck typing / structural checks.importlib.reload is fine for modules that only expose functions
(no class definitions whose instances live elsewhere). Functions don't
have the same identity-leak problem because nothing typically does
isinstance(obj, some_func).importlib.reload--boxed flagWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub cajias/claude-skills --plugin python-tooling5 skills in this plugin
/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"`.
/python-slots-mock-patch-objectFix 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).
/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`.
Other plugins' skills for the same job