Skip to content

Static typing (closes #196) - #218

Merged
ilia-kats merged 38 commits into
mainfrom
typing
Oct 29, 2026
Merged

ilia-kats merged 38 commits into
mainfrom
typing

Conversation

@ilia-kats

@ilia-kats ilia-kats commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Static typing and mypy pre-commit hooks. This targets the anndata main branch (hence the failing mypy and RTD in CI). There are a lot of type: ignore comments at the moment, the vast majority of them belongs to one of the following three cases:

  • mudata uses AnnData internals that are typed with AnnData but work just fine with MuData (e.g. AlignedMapping and related)
  • similarly, accessors were not meant to be subclassed and are not typed with that in mind. Also, the type system generally does not seem to handle mixin classes particularly well
  • accesses to AnnData.X or AnnData.layers. These are currently typed as Any:
    from anndata import AnnData
    from typing import reveal_type
    
    adata = AnnData()
    
    reveal_type(adata.X)
    prints
    test.py:6: note: Revealed type is "numpy.ndarray[tuple[Any, ...], numpy.dtype[Any]] | Any | dask.array.core.Array | anndata.types.SupportsArrayApiBase | h5py._hl.dataset.Dataset | zarr.core.array.Array[Any] | anndata.abc.CSRDataset | anndata.abc.CSCDataset | xarray.core.dataarray.DataArray | anndata._core.xarray.Dataset2D | None"
    
    I'm not sure, but I think this is due to the way optional dependencies are handled in compat. I don't know how to best solve this. The only option I can think of is to construct the type unions only with the available packages and only do the mock types when building docs. But I don't know if mypy will be able to handle the conditional logic, and this has the downside that code written by someone without opt deps may not typecheck with the opt deps.

@autofix-troubleshooter

Copy link
Copy Markdown

Hi! I'm the autofix logoautofix.ci troubleshooter bot.

It looks like you correctly set up a CI job that uses the autofix.ci GitHub Action, but the autofix.ci GitHub App has not been installed for this repository. This means that autofix.ci unfortunately does not have the permissions to fix this pull request. If you are the repository owner, please install the app and then restart the CI workflow! 😃

@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.19%. Comparing base (6038e1a) to head (39ff1b3).

Files with missing lines Patch % Lines
src/mudata/_core/io.py 83.92% 9 Missing ⚠️
src/mudata/_core/merge.py 64.28% 5 Missing ⚠️
src/mudata/_core/repr.py 72.72% 3 Missing ⚠️
src/mudata/_core/mudata.py 98.18% 2 Missing ⚠️
src/mudata/_core/to_.py 71.42% 2 Missing ⚠️
src/mudata/acc/__init__.py 93.10% 2 Missing ⚠️
src/mudata/_core/file_backing.py 96.15% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #218      +/-   ##
==========================================
- Coverage   91.28%   90.19%   -1.09%     
==========================================
  Files          12       12              
  Lines        1847     1856       +9     
==========================================
- Hits         1686     1674      -12     
- Misses        161      182      +21     
Files with missing lines Coverage Δ
src/mudata/_core/utils.py 95.18% <100.00%> (+1.20%) ⬆️
src/mudata/_core/views.py 100.00% <100.00%> (ø)
src/mudata/_core/file_backing.py 92.77% <96.15%> (-0.26%) ⬇️
src/mudata/_core/mudata.py 93.55% <98.18%> (+0.02%) ⬆️
src/mudata/_core/to_.py 89.28% <71.42%> (-2.72%) ⬇️
src/mudata/acc/__init__.py 87.81% <93.10%> (+0.38%) ⬆️
src/mudata/_core/repr.py 55.04% <72.72%> (-12.25%) ⬇️
src/mudata/_core/merge.py 82.22% <64.28%> (-1.12%) ⬇️
src/mudata/_core/io.py 93.88% <83.92%> (-1.81%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ilia-kats ilia-kats linked an issue Oct 16, 2026 that may be closed by this pull request

@Zethson Zethson 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.

This targets the anndata main branch (hence the failing mypy and RTD in CI).

https://github.com/scverse/pertpy/blob/main/pyproject.toml#L155 should also work for you, right?

similarly, accessors were not meant to be subclassed and are not typed with that in mind.

I think that's feedback for @flying-sheep and @ilan-gold. Maybe there are quick improvements. Otherwise, no big deal.

accesses to AnnData.X or AnnData.layers. These are currently typed as Any:

Same for this.

Generally, I feel like this PR is absolutely a step into the right direction.

Comment thread src/mudata/_core/io.py Resolved
Comment thread src/mudata/_core/io.py Resolved
Comment thread src/mudata/_core/io.py
stacklevel=1,
)
d = {}
d: dict[str, Any] = {}

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.

Nit: Can this Any be specified more closely? Should be possible, right?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It doesn't seem so, at least not without blowing up the code by a lot. I can do d: dict[str, RWAble], but then mypy throws

src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "AnnData | Mapping[str, AnnData | MuData] | MuData | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, str] | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Literal[0, 'obs', 1, 'var', -1, 'both']"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "DataFrame | Series[Any] | Index[Any] | Mapping[str, Iterable[Any]] | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "ndarray[tuple[Any, ...], dtype[Any]] | Mapping[str, Sequence[Any]] | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, Any] | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, ndarray[tuple[int], dtype[unsignedinteger[Any]]]] | None"  [arg-type]
src/mudata/_core/io.py:432: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "bool"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "AnnData | Mapping[str, AnnData | MuData] | MuData | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, str] | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Literal[0, 'obs', 1, 'var', -1, 'both']"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "DataFrame | Series[Any] | Index[Any] | Mapping[str, Iterable[Any]] | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "ndarray[tuple[Any, ...], dtype[Any]] | Mapping[str, Sequence[Any]] | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, Any] | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "Mapping[str, ndarray[tuple[int], dtype[unsignedinteger[Any]]]] | None"  [arg-type]
src/mudata/_core/io.py:471: error: Argument 1 to "MuData" has incompatible type "**dict[str, Storable | AnnData | ExtensionArray]"; expected "bool"  [arg-type]

So either explicitly test / cast all the dict elements, or it stays like this.

Comment thread src/mudata/_core/io.py
f = zarr.open(store, mode="r")
d = {}
f = zarr.open_group(store, mode="r")
d: dict[str, Any] = {}

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.

Also this one

Comment thread src/mudata/_core/merge.py Resolved
Comment thread src/mudata/_core/merge.py Resolved
Comment thread pyproject.toml Resolved
@ilia-kats

ilia-kats commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

https://github.com/scverse/pertpy/blob/main/pyproject.toml#L155 should also work for you, right?

Yeah, I'll add something like this when this gets closer to merging, the point for now was to just get feedback from you and @ilan-gold .

I think that's feedback for @flying-sheep and @ilan-gold.

That's why I also tagged @ilan-gold here.

@flying-sheep

flying-sheep commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

similarly, accessors were not meant to be subclassed and are not typed with that in mind

as the docs explicitly state, they are meant to be subclassed, or what do you mean?

how can the typing be improved?

accesses to AnnData.X or AnnData.layers. These are currently typed as Any […] I'm not sure, but I think this is due to the way optional dependencies are handled in compat.

The if TYPE_CHECKING in the conditions means that type checkers always see the real import, and using try/except would do the same.

the only ways to remove the Any are

  • install cupy
  • use stubs (locally like fast-array-utils does or by publishing a cupy-stubs package)

option 1 would work immediately, option 2 is a little work.

@ilia-kats

Copy link
Copy Markdown
Collaborator Author

as the docs explicitly state, they are meant to be subclassed, or what do you mean?

how can the typing be improved?

The most common issue that mypy complaines about is that the signature of .get() is incompatible with the base class, which makes sense: My .get only accept MuData objects, while the base is typed with AnnData | MuData. Mudata accessors won't work with AnnData objects, so the typing has to stay. I see two options here: Leave as-is, or make it another generic argument.

Another thing that mypy complains about is Type argument "R" of "LayerAcc" must be a subtype of "AdRef[tuple[str | slice[Any, Any, Any], slice[Any, Any, Any]] | tuple[slice[Any, Any, Any], str | slice[Any, Any, Any]], AnnData]", which again for me is typed with MuData.

Simiarly, the to/from_json methods have different return types for me, which mypy again complains about. Here I'm not sure if anything can be done at all.

The if TYPE_CHECKING in the conditions means that type checkers always see the real import, and using try/except would do the same.

So that means everyone type checking their anndata use needs to have all opt deps (or their stubs) installed? To me that seems like it sort of defeats the point of making them optional in the first place.

@flying-sheep

flying-sheep commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Thanks! Yeah you and Ilan already added MuData as generic options there, seems like it needs more work.

Regarding my comment above: I made cupy-stubs because of this, see scverse/anndata#2716

So that means everyone type checking their anndata use needs to have all opt deps (or their stubs) installed?

I wish it was different. It’s insane how easy it is to have Any sneak in, mypy should really really give us tools to avoid this.

Comment thread src/mudata/_core/io.py Resolved
Comment thread src/mudata/_core/io.py
file = zarr.open(store, mode="w", zarr_format=zarr_format)
file = zarr.open_group(store, mode="w", zarr_format=zarr_format)
except TypeError:
# zarr_format is not supported in this version of zarr

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Does MuData still need to support zarr-python<3? anndata doesn't https://github.com/scverse/anndata/blob/0.13.4/pyproject.toml#L47 (not for this PR, just a comment)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

mudata supports anndata>=0.11, so yes, we still need Zarr 2 support

Comment thread src/mudata/_core/io.py
Comment on lines +445 to +447
if backed and (isinstance(filename, IOBase) or _is_openfile(filename)):
warn("Backed mode is not supported if `filename` is an open file. Switching off backed mode.", stacklevel=1)
backed = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why not error here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Why should we? This is not something unrecoverable, we can still read the file.

Comment thread src/mudata/_core/io.py
mods[m] = _read_mod_extras(gmods[m], read_elem(gmods[m]))
if not isinstance(mod := gmods[m], zarr.Group):
raise ValueError(f"Modality {m} must be a group.")
mods[m] = _read_mod_extras(mod, cast(AnnData, read_elem(gmods[m])))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do our read_{zarr,h5ad} methods not handle groups? I think they do. That might allow you to avoid the cast

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

read_h5ad does not. read_zarr does, but it just reads everything that's there and passes that as kwargs to the anndata constructor, which now conflicts with the treedata extras (TypeError: AnnData.__init__() got an unexpected keyword argument 'extra').

return f"A.mod[{self.mod}]"

def to_json(self, ref: R) -> list[str | int | None]:
def to_json(self, ref: R) -> list[str | list[str | int | None]]: # type: ignore[override]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So this is something we should resolve upstream?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I don't think the to/from_json issues can be resolved at all (it's a different schema for MuData), but the other two accessor issues I mentioned are probably best addressed upstream, if we want to resolve them.

@ilia-kats ilia-kats Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Having looked into the other points, I don't see a simple way to make .get() generic in its data argument. Ideally, I'd like to do something like

class MetaAcc[D: AnnData | MuData, R: AdRef[str | None, D])(RefAcc[R, str | None, D]):
    def get(self, data: D)

but apparently passthrough of type vars to nested generics is not supported in Python. So the only solution that I can see is introducing yet another typevar throughout the class hierarchy and duplicating the types everywhere.

I'm not super invested in static typing, so I'm also fine just leaving the type: ignore comments in place.

/edit: python/typing#548 seems related

@ilia-kats

Copy link
Copy Markdown
Collaborator Author

If there are no more comments, I'd like to merge this rather soon-ish.

@Zethson

Zethson commented Oct 28, 2026

Copy link
Copy Markdown
Member

@ilia-kats ship it! This can always be iterated on

@ilia-kats
ilia-kats merged commit 84be703 into main Oct 29, 2026
7 of 12 checks passed
@ilia-kats
ilia-kats deleted the typing branch October 29, 2026 08:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fully type

5 participants