Skip to content

build: sync with cookiecutter-scverse template, adopt mypy - #2577

Merged
flying-sheep merged 70 commits into
mainfrom
template-sync-typing
Aug 4, 2026
Merged

flying-sheep merged 70 commits into
mainfrom
template-sync-typing

Conversation

@Zethson

@Zethson Zethson commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Syncs the repo config with cookiecutter-scverse main (707f3fa, up from v0.6.0) and adopts the template's mypy hook.

Template sync — pre-commit hook set, .editorconfig, biome.jsonc, Typing :: Typed. pre-commit.ci is replaced by a Pre-commit checks CI job plus a pre-commit Dependabot ecosystem, which makes the standalone codespell workflow redundant. Deliberate deviation: taplo is kept over pyproject-fmt, since it also formats hatch.toml.

Typing — mypy over src and tests, configured in [tool.mypy]. Stubs for pandas, scipy, psutil, tqdm, jsonschema and boltons; installed-but-untyped dependencies are read from source via follow_untyped_imports rather than collapsing to Any; ignore_missing_imports is scoped to the optional dependencies absent at check time. No # type: ignore anywhere.

The rest of the commits are the fixes this surfaced. Notable real bugs: filename() raised AttributeError on every zarr node (store.path is gone in zarr v3); _read_attr raised TypeError whenever a default was passed; obs_keys()/var_keys() crashed on xarray-backed objects; write_loom emitted a None-named layer; __sizeof__ crashed on COO in uns; xp.ravel/xp.where(cond)/xp.array/xp.promote_types are not in the array API standard; and four tests were asserting vacuously.

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.69643% with 149 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.63%. Comparing base (318c93b) to head (63f419d).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/anndata/_core/anndata.py 86.60% 15 Missing ⚠️
src/anndata/_io/read.py 60.00% 14 Missing ⚠️
src/anndata/experimental/pytorch/_annloader.py 14.28% 12 Missing ⚠️
src/anndata/_core/raw.py 74.41% 11 Missing ⚠️
src/anndata/_core/sparse_dataset.py 87.50% 11 Missing ⚠️
src/anndata/experimental/merge.py 78.00% 11 Missing ⚠️
src/anndata/_io/write.py 28.57% 10 Missing ⚠️
src/anndata/utils.py 67.74% 10 Missing ⚠️
src/anndata/_core/views.py 78.57% 9 Missing ⚠️
src/anndata/_core/aligned_mapping.py 92.59% 8 Missing ⚠️
... and 12 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2577      +/-   ##
==========================================
- Coverage   87.83%   85.63%   -2.20%     
==========================================
  Files          49       49              
  Lines        7799     8057     +258     
==========================================
+ Hits         6850     6900      +50     
- Misses        949     1157     +208     
Files with missing lines Coverage Δ
src/anndata/__init__.py 80.95% <100.00%> (-0.87%) ⬇️
src/anndata/_core/aligned_df.py 96.77% <100.00%> (+0.05%) ⬆️
src/anndata/_core/storage.py 95.31% <100.00%> (ø)
src/anndata/_io/specs/lazy_methods.py 96.53% <100.00%> (+0.21%) ⬆️
src/anndata/_io/specs/methods.py 91.77% <100.00%> (+0.05%) ⬆️
src/anndata/_io/specs/registry.py 94.88% <100.00%> (ø)
src/anndata/_io/utils.py 75.46% <100.00%> (+0.61%) ⬆️
src/anndata/_types.py 100.00% <100.00%> (ø)
src/anndata/_warnings.py 83.33% <ø> (-0.88%) ⬇️
src/anndata/abc.py 100.00% <100.00%> (ø)
... and 30 more

... and 1 file with indirect coverage changes

@Zethson
Zethson force-pushed the template-sync-typing branch from a8869f3 to a760d84 Compare July 29, 2026 16:38
@Zethson Zethson added this to the 0.14.0 milestone Jul 29, 2026
@Zethson
Zethson marked this pull request as ready for review July 30, 2026 08:02
@flying-sheep

flying-sheep commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

very cool! I think there are some parts that probably need to be refactored to support static typing properly, e.g. the aligned mapping stuff might be too cute for type checkers to understand. Mixins, associated classes which are generic and therefore would need higher-kinded typevars … maybe we can work around all this without a refactor, but maybe not.

I’ve ranted against Python’s type checker but watched this recently: https://www.youtube.com/watch?v=0BXuYlNrUmE

  • Python’s type checking is still underpowered – having e.g. a useful numpy-style signature with dtype parameter is a huge PITA
  • But maybe some code bases can be refactored to simply use simpler types

@Zethson
Zethson force-pushed the template-sync-typing branch from 0c25bd7 to 8e733a4 Compare July 30, 2026 08:13
@Zethson

Zethson commented Jul 30, 2026 •

Copy link
Copy Markdown
Member Author

@flying-sheep glad you like it already! I actually had wanted to write a long message with some context so here we go:

I'm pushing for this because I am currently trying to ensure that all of our projects adhere to the latest template version. This is a pet peeve of mine and I just want to get it done. While doing so, I thought - why not move immediately to the upcoming version 1.0 with typing? Doing so for pertpy, I noticed that neither AnnData or scanpy are fully typed yet (or at least labeled as such via py.typed) making this effort a bit less meaningful. So my plan is to slowly get our fundamental packages typed (so also MuData & SpatialData soon) and then go from there.

This PR therefore mixes two concerns:

  1. From template 0.old to 1.0.0 pre-release
  2. Adopting mypy

If you insist, we can disentangle these two things into two PRs but I'm fine with just being pragmatic and solving everything in one go.

Implementation wise, this is mostly a human guided Claude Opus 5 high effort PR that cost a few hundred $ in tokens. The initial mypy run gave us ~2000 errors. I am worried that this would be too many errors to fix by hand and therefore this would have never been done. So I think it's a best effort approach to start with this LLM based PR.

@flying-sheep @ilan-gold As a result of that, I suggest that I'll have another look at the PR to fix anything I notice to be off and then hand this PR over to you. I don't want to be the "just did some LLM PR and then let others do the actual work aka reviewing it" but I think your advanced typing experience is a little bit beyond mine and you know the code base better.

I'd be happy if we could give this PR priority, please because it touches so many places. If we let this PR sit for too long, we'll keep fighting PR conflicts and end up wasting our time.

Does this sound okay with you?

I'll have a look now so after lunch, this PR will be ready for you.
Thanks!

@Zethson

Zethson commented Jul 30, 2026

Copy link
Copy Markdown
Member Author

Implementation notes:

  1. This PR removes codespell because the template doesn't have it. Let me know if you insist on keeping it. No strong feelings.
  2. pre-commit CI is expected to fail. After this PR is merged, we'll disable it.

@flying-sheep

flying-sheep commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

or at least labeled as such via py.typed

anndata is since very shortly ago!

If you insist, we can disentangle these two things into two PRs but I'm fine with just being pragmatic and solving everything in one go.

I’m fine with that too, the typing change is the biggest part of the new template update.

Does this sound okay with you?

Yeah. I’m happy with it because despite LLMs producing especially subtle logic errors compared to humans, I always get tripped up by “what’s a mypy bug and what’s an actual typing issue” myself, so maybe Claude did a better job than I could ever have done (even if I had spent weeks focusing on this).

If we find typing issues, we can fix them.

I'll have a look now so after lunch, this PR will be ready for you.

great, just request my review once you’re ready.

Comment thread docs/api.md Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/experimental/merge.py Resolved
Comment thread src/anndata/tests/helpers.py Resolved
Comment thread .cruft.json
"directory": null
"template": "https://github.com/scverse/cookiecutter-scverse",
"commit": "707f3faab836f9272912f92188b63b31da70c064",
"checkout": "main",

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably not be main but 0.8.0 or something for now. There'll just be less merge conflicts later when the 1.0.0 sync runs

Comment thread .pre-commit-config.yaml Resolved
Comment thread pyproject.toml Resolved

@flying-sheep flying-sheep left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs the setup from scverse/cookiecutter-scverse#540

after this PR also strict = true

@Zethson

Zethson commented Jul 30, 2026 •

Copy link
Copy Markdown
Member Author

@flying-sheep you're making these changes now right? Then I won't also change the setup. I was just about to address your last request.

@flying-sheep

flying-sheep commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

I’m on it, getting a little hands-on helps me understand the changes better anyway.

you could do the AnnCollection thing that’s pretty self-contained.

Comment thread .github/workflows/codespell.yml Resolved

@flying-sheep flying-sheep left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, reviewed aligned_mapping

Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/aligned_mapping.py Resolved
Comment thread src/anndata/_core/anndata.py Resolved
Comment thread src/anndata/_core/file_backing.py Resolved
Comment thread src/anndata/acc/__init__.py Resolved
Comment thread src/anndata/_io/specs/lazy_methods.py Resolved
Comment thread src/anndata/acc/__init__.py Resolved
Comment thread pyproject.toml Resolved
Comment thread tests/accessors/test_accessors.py Resolved
Zethson added 2 commits August 4, 2026 09:47
Realign the repo configuration with the template on main:

- pre-commit: `fail_fast`/`default_stages`/`minimum_pre_commit_version`
  preamble, `check-ast`, `mixed-line-ending`, `--assume-in-merge` for
  `check-merge-conflict`, `--exit-non-zero-on-fix` for ruff, notebooks in
  `types_or`, `--no-progress --fix` for zizmor, and `.cruft.json` excluded
  from biome so cruft’s own indentation survives a template update.
- Replace pre-commit.ci with the template’s model: a `Pre-commit checks`
  job in the CPU workflow wired into the `check` gate, plus a `pre-commit`
  Dependabot ecosystem to keep hook versions current. The separate
  codespell workflow is redundant now that every hook runs in CI.
- editorconfig: `.cruft.json` at 2 spaces and tabs in Makefiles; biome
  schema 2.2.0 with `vcs` so it honours `.gitignore`.
- `Typing :: Typed` classifier.

Adopt the template’s mypy hook over `src` and `tests`, configured through
`[tool.mypy]`. Stub packages cover pandas, scipy, psutil, tqdm, jsonschema
and boltons; dependencies that ship no `py.typed` but are installed are
analyzed from source via `follow_untyped_imports` rather than collapsing
to `Any`, and `ignore_missing_imports` is scoped to the optional
dependencies that are absent when type checking.

Keep taplo rather than switching to pyproject-fmt: it formats `hatch.toml`
too, which the template has no equivalent of.
Type checking `src` and `tests` turns up code that cannot work:

- `filename()` returned `x.store.path` for zarr nodes, but zarr v3 stores
  have no `path`, so every call raised `AttributeError`. Use the store’s
  URL, which is what the one caller compares against.
- `get_memory_usage()` fell back to `Process.get_memory_info()`, removed
  in psutil 2.0, and `print_memory_usage()` passed the keyword-only
  `newline` positionally, tripping the `old_positionals` deprecation.
- `acc.parse()` parsed twice for `strict=False`, discarding the first
  result; split the body out so the non-strict path just catches.
- `_types` imported `AnnDataElem` from itself, shadowing the definition
  below it.
- `convert_dictionary_to_structured_array()` iterated `dtype.names`, which
  is `None` for unstructured dtypes; iterate the field list it was built
  from instead.

`SupportsArrayApiBase` declared `device`/`shape`/`size` as settable
attributes, which no array implementation satisfies, and omitted `dtype`
and `ndim`; both are mandated by the array API standard. Declaring them as
read-only properties lets real arrays match structurally. The array-API
test double gains the two attributes it was missing.

Also replace `~index.isna()` with `index.notna()`, name the walrus targets
in `parse_json` so they stop shadowing the matched sequence, and rebind
`CSRDataset`/`CSCDataset`’s abstract methods through a decorator instead
of a module-level loop.
@flying-sheep
flying-sheep force-pushed the template-sync-typing branch from a8f0b7f to 63f419d Compare August 4, 2026 07:47
@flying-sheep
flying-sheep merged commit e0926ca into main Aug 4, 2026
21 of 22 checks passed
@flying-sheep
flying-sheep deleted the template-sync-typing branch August 4, 2026 08:11
@flying-sheep

Copy link
Copy Markdown
Member

@Zethson you forgot autofix, could you please implement that?

@Zethson

Zethson commented Aug 4, 2026

Copy link
Copy Markdown
Member Author

@flying-sheep do you mean the ruff config option?

Zethson added a commit to scverse/pertpy that referenced this pull request Aug 4, 2026
Replaces 172 inline `# type: ignore[import-untyped]` comments with the two
`[[tool.mypy.overrides]]` buckets anndata adopted in scverse/anndata#2577:
`follow_untyped_imports` for dependencies that are installed but ship no
`py.typed`, and `ignore_missing_imports` for the rest.

Two deviations from anndata's config are forced:

- `explicit_package_bases` is omitted. anndata's type-check environment lives
  outside its repository, pertpy's `.venv` does not, so mypy resolves
  site-packages modules under two names and refuses to continue.
- `statsmodels` goes in the second bucket. Its `api.py` re-exports through
  `from .__init__ import test`, which mypy cannot follow.

Actually following the untyped dependencies surfaced several real bugs:

- `ToyTree.idx_dict` does not exist on toytree >=3 (it is `_idx_dict`), so
  tascCODA raised `AttributeError` at runtime. Now uses the public `tree[idx]`
  and iteration API.
- `az.summary(data=..., *args)` unpacked star-args after keyword arguments, so
  any positional argument bound to `data` and raised. The passthrough could
  never work; it is removed.
- `NUTS`/`HMC` were called with a hard-coded `init_strategy=`, so passing
  `init_strategy` yourself raised "multiple values". It is now a `setdefault`.
- Two `Milo` plots never forwarded `return_fig`, so `return_fig=True` returned
  an `Axes` rather than a `Figure`.
- `adata.raw` was dereferenced unguarded in three CINEMA-OT paths.
- `Compound.from_cid` was passed a `str` where pubchempy wants an `int` CID.
- `make_nhoods` built its vertex index as float64, so it indexed a sparse
  matrix with floats.

`CompositionalModel2.prepare` violated LSP against both subclasses; it is a
`super()`-only helper and is now `_prepare`. `rank_genes_groups`'s `method`
parameter is typed with the literal scanpy declares instead of `str`.

The deprecated `sc.pp.subsample` is replaced by `sc.pp.sample`, which is
overloaded on `copy` and so returns `AnnData` rather than a union. `sample`
draws from a different generator than `subsample` did, so the sampled cells
change and the affected regression values are updated. Where `subsample`'s
implicit `random_state=0` was relied on, the seed is now an explicit
`random_state` parameter rather than a hard-coded constant. The two Augur
score assertions are keyed by cell type, since the column order of
`summary_metrics` is not stable across runs.

anndata becomes a direct dependency, since pertpy imports it directly. It is
left unpinned because 0.14 is unreleased; a `[tool.uv.sources]` entry supplies
main for type checking, which uv reads and pip ignores so installs stay
resolvable.
Zethson added a commit to scverse/pertpy that referenced this pull request Aug 4, 2026
* build: adopt anndata's mypy configuration

Replaces 172 inline `# type: ignore[import-untyped]` comments with the two
`[[tool.mypy.overrides]]` buckets anndata adopted in scverse/anndata#2577:
`follow_untyped_imports` for dependencies that are installed but ship no
`py.typed`, and `ignore_missing_imports` for the rest.

Two deviations from anndata's config are forced:

- `explicit_package_bases` is omitted. anndata's type-check environment lives
  outside its repository, pertpy's `.venv` does not, so mypy resolves
  site-packages modules under two names and refuses to continue.
- `statsmodels` goes in the second bucket. Its `api.py` re-exports through
  `from .__init__ import test`, which mypy cannot follow.

Actually following the untyped dependencies surfaced several real bugs:

- `ToyTree.idx_dict` does not exist on toytree >=3 (it is `_idx_dict`), so
  tascCODA raised `AttributeError` at runtime. Now uses the public `tree[idx]`
  and iteration API.
- `az.summary(data=..., *args)` unpacked star-args after keyword arguments, so
  any positional argument bound to `data` and raised. The passthrough could
  never work; it is removed.
- `NUTS`/`HMC` were called with a hard-coded `init_strategy=`, so passing
  `init_strategy` yourself raised "multiple values". It is now a `setdefault`.
- Two `Milo` plots never forwarded `return_fig`, so `return_fig=True` returned
  an `Axes` rather than a `Figure`.
- `adata.raw` was dereferenced unguarded in three CINEMA-OT paths.
- `Compound.from_cid` was passed a `str` where pubchempy wants an `int` CID.
- `make_nhoods` built its vertex index as float64, so it indexed a sparse
  matrix with floats.

`CompositionalModel2.prepare` violated LSP against both subclasses; it is a
`super()`-only helper and is now `_prepare`. `rank_genes_groups`'s `method`
parameter is typed with the literal scanpy declares instead of `str`.

The deprecated `sc.pp.subsample` is replaced by `sc.pp.sample`, which is
overloaded on `copy` and so returns `AnnData` rather than a union. `sample`
draws from a different generator than `subsample` did, so the sampled cells
change and the affected regression values are updated. Where `subsample`'s
implicit `random_state=0` was relied on, the seed is now an explicit
`random_state` parameter rather than a hard-coded constant. The two Augur
score assertions are keyed by cell type, since the column order of
`summary_metrics` is not stable across runs.

anndata becomes a direct dependency, since pertpy imports it directly. It is
left unpinned because 0.14 is unreleased; a `[tool.uv.sources]` entry supplies
main for type checking, which uv reads and pip ignores so installs stay
resolvable.

* fix: support mudata 0.4

mudata 0.4 drops `set_options` and makes `pull_on_update=False` the default,
so the call is only needed on 0.3.
Zethson added a commit to scverse/spatialdata that referenced this pull request Aug 29, 2026
Follows the approach of scverse/anndata#2577: dependencies that are
installed but ship no py.typed marker are read from source through
follow_untyped_imports rather than collapsing to Any, and
ignore_missing_imports is scoped to the optional dependencies that are
absent when the check runs. Reading real types out of ome_zarr, pyarrow,
dask_image and friends surfaces more errors, not fewer, which is the
point.

Narrowing is written out at each site rather than routed through a
generic helper, because a helper taking `object` and returning a
concrete type is a cast wearing a hat.

Fixed here:
- Indexing a zarr group and opening a zarr store both yield Array | Group,
  while every reader and writer here needs a Group.
- store.root exists only on LocalStore, so reading or writing the parquet
  file of a points or shapes element now says so instead of failing with
  AttributeError on any other store.
- coordinateTransformations and the spatialdata attrs payload are typed as
  arbitrary JSON and were indexed without being checked.
- _resolve_zarr_store() returns a Store on every path but was annotated
  StoreLike, which made every .close() and .root on the result an error.
- read_zarr() rebound its attrs dict to None, and DataArray.dims is a
  tuple of Hashable rather than of str.

460 errors left, down from 500. Tests stay green.

Signed-off-by: Lukas Heumos <lukas.heumos@posteo.net>
barlowa124 pushed a commit to barlowa124/anndata that referenced this pull request Dec 4, 2026
)

Co-authored-by: Philipp A. <flying-sheep@web.de>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants