Repository navigation
build: sync with cookiecutter-scverse template, adopt mypy - #2577
Conversation
Codecov Report❌ Patch coverage is 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
|
a8869f3 to
a760d84
Compare
|
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
|
0c25bd7 to
8e733a4
Compare
|
@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:
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. |
|
Implementation notes:
|
anndata is since very shortly ago!
I’m fine with that too, the typing change is the biggest part of the new template update.
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.
great, just request my review once you’re ready. |
| "directory": null | ||
| "template": "https://github.com/scverse/cookiecutter-scverse", | ||
| "commit": "707f3faab836f9272912f92188b63b31da70c064", | ||
| "checkout": "main", |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
needs the setup from scverse/cookiecutter-scverse#540
after this PR also strict = true
|
@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. |
|
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. |
flying-sheep
left a comment
There was a problem hiding this comment.
OK, reviewed aligned_mapping
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.
a8f0b7f to
63f419d
Compare
|
@Zethson you forgot autofix, could you please implement that? |
|
@flying-sheep do you mean the ruff config option? |
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.
* 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.
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>
Syncs the repo config with cookiecutter-scverse
main(707f3fa, up fromv0.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 aPre-commit checksCI job plus apre-commitDependabot ecosystem, which makes the standalone codespell workflow redundant. Deliberate deviation: taplo is kept over pyproject-fmt, since it also formatshatch.toml.Typing — mypy over
srcandtests, configured in[tool.mypy]. Stubs for pandas, scipy, psutil, tqdm, jsonschema and boltons; installed-but-untyped dependencies are read from source viafollow_untyped_importsrather than collapsing toAny;ignore_missing_importsis scoped to the optional dependencies absent at check time. No# type: ignoreanywhere.The rest of the commits are the fixes this surfaced. Notable real bugs:
filename()raisedAttributeErroron every zarr node (store.pathis gone in zarr v3);_read_attrraisedTypeErrorwhenever a default was passed;obs_keys()/var_keys()crashed on xarray-backed objects;write_loomemitted aNone-named layer;__sizeof__crashed on COO inuns;xp.ravel/xp.where(cond)/xp.array/xp.promote_typesare not in the array API standard; and four tests were asserting vacuously.