Skip to content

Five behaviour changes introduced by the mypy adoption in #411 (visium() is unusable) #417

Closed

Description

@LucaMarconato

AI-generated issue, not reviewed yet

Summary

#411 enabled mypy over src and tests with an explicit "no # type: ignore, no casts" policy. Most of that work is fine, but in five places a type error was silenced by restructuring code rather than by annotating it, and the restructuring changed behaviour. One of them makes visium() unusable.

All five are reproduced below on main (d2664fa), Python 3.13, spatialdata 0.8.0, tifffile 2026.9.9, anndata 0.13.3.


1. visium() raises for every dataset 🔴

from spatialdata_io import visium
visium("CytAssist_FFPE_Human_Breast_Cancer", dataset_id="breast")
TypeError: ShapesModel.parse() does not support the type <class 'pandas.core.frame.DataFrame'>

The whole of #411's diff to visium.py is three lines:

+    assert isinstance(adata.obs, pd.DataFrame)
     adata.obs = pd.merge(adata.obs, coords, how="left", left_index=True, right_index=True)
-    coords = adata.obs[[VisiumKeys.SPOTS_X, VisiumKeys.SPOTS_Y]].values
-    adata.obsm["spatial"] = coords
+    adata.obsm["spatial"] = adata.obs[[VisiumKeys.SPOTS_X, VisiumKeys.SPOTS_Y]].values

coords held two different things in sequence: the pd.read_csv() table of tissue positions (used for the merge into adata.obs), and then, after the rebinding, the (n, 2) array of spot coordinates that ShapesModel.parse() consumes 45 lines below. Inlining the expression removed the rebinding, so the raw five-column table reaches parse(), which registers only np.ndarray, str/Path and GeoDataFrame.

A variable changing type across a reassignment is exactly what mypy rejects (Incompatible types in assignment); the assert isinstance(adata.obs, pd.DataFrame) added on the line above is the tell.

The plain Visium reader has no test, which is why a hard TypeError on the first call survived a full CI run. prepare_test_data.yaml downloads Visium HD but no plain Visium dataset.

2. merscope() no longer falls back when rioxarray cannot be imported

-    try:
-        import rioxarray
-        return _rioxarray_load_merscope
-    except ModuleNotFoundError:
-        return _dask_image_load_merscope
+    if importlib.util.find_spec("rioxarray") is not None:
+        return _rioxarray_load_merscope
+    return _dask_image_load_merscope

find_spec reports whether a module can be found, not whether importing it succeeds. With a rioxarray whose rasterio is broken — a common way for this dependency to be half-present:

# rioxarray.py on sys.path: raise ModuleNotFoundError("No module named 'rasterio'")
importlib.util.find_spec("rioxarray") is not None   # True
_get_reader(None)                                   # _rioxarray_load_merscope  (was: _dask_image_load_merscope)

and calling it fails with ModuleNotFoundError: Using rioxarray backend requires to install the rioxarray library (pip install rioxarray) — which misdescribes the cause and leaves the user with no working backend, where before the reader quietly used dask_image.

3. dbit() without a path now reads the current working directory

-    if path is not None:
-        path = Path(path)
-        if not os.path.isdir(path):
-            raise FileNotFoundError(...)
+    path = Path() if path is None else Path(path)
+    if not os.path.isdir(path):
+        raise FileNotFoundError(...)

path is optional in the signature. Path() is ., which is always a directory, so dbit() with no arguments now searches the process's cwd and reads whatever .h5ad and barcode file happen to be there:

$ cd /some/unrelated/dir && python -c "from spatialdata_io import dbit; dbit()"
WARNING mydata.h5ad is used.
WARNING barcode_list.txt is used.

Before #411 that combination raised (Path.joinpath(None, ...) → AttributeError). Turning a crash into "quietly reads from cwd" is the wrong direction, and the FileNotFoundError above is now unreachable for path=None. The change was made to drop a # type: ignore on the _check_path(path=path) calls.

4. macsima() aborts on a folder containing one unparsable file

-            except Exception:
+            except (OSError, ValueError, IndexError, NotImplementedError):
                 logger.debug(f"Could not parse physical size from {p}. Trying next file.")

The loop's own comment is "Iterate over path files, as it may still contain invalid files", so the exception list has to cover everything ome_types.from_tiff() can raise. It does not — a TIFF with a valid header truncated before its metadata raises struct.error, which derives directly from Exception:

# a real OMAP10 tif truncated to 200 bytes, dropped into the folder
macsima("OMAP10_small")
# struct.error: unpack requires a buffer of 8 bytes

Two notes:

  • MultiChannelImage.from_paths() has the same problem with except ValueError and, being reached first, is what actually raises today. That guard predates Adopt the current scverse cookiecutter template #411, but the two compound: fix from_paths alone and the file then reaches create_sdata, where Adopt the current scverse cookiecutter template #411's narrowing aborts the reader. Verified by reverting each fix separately.
  • tifffile.TiffFileError derives from ValueError in tifffile 2026.9.9 and from Exception in older releases, so the enumeration is also version-dependent.

Enumerating the failure modes of a third-party parser applied to arbitrary user files cannot be done correctly; both call sites exist precisely to tolerate unparsable files.

5. macsima() truncates the OME plane positions

-        translations = {"translation_x": ome...position_x, "translation_y": ome...position_y}
+            translations = {"translation_x": int(position_x), "translation_y": int(position_y)}

This one is mostly a fix, and the PR describes it as such: the values are used as da.pad widths in MultiChannelImage._pad_images, and da.pad rejects floats, so before #411 any dataset with plane positions crashed in padding. But int() truncates towards zero rather than rounding, so position_x = 0.9 becomes a 0 offset and every tile offset is biased towards the origin.

Two related things worth a separate look, which I have not changed:

  • OME Plane.position_x/position_y are stage coordinates with their own unit (position_x_unit, typically µm), and _pad_images consumes them directly as pixel counts, without using pixels_to_microns. If a real MACSima export sets them in µm, the padding is scaled wrong.
  • Every TIFF in data/OMAP10_small and data/OMAP23_small has position_x = position_y = None, so CI only ever exercises the (0, 0) default: the int()/round() conversion and the whole translation-aware padding path (Pad images with 0 on right and bottom, if images differ in dimensions #371) have no coverage.

Minor, no change proposed

  • xenium: if cell_polys is not None (added for _get_polygons() -> GeoDataFrame | None) is dead code today — the only return None is guarded by is_nucleus — but its semantics are wrong for cells: if it ever becomes reachable, a caller that passed cells_boundaries=True gets an object silently missing that element, with no warning.
  • curio: the refactor moved obs[INSTANCE_KEY] = obs.index before adata.obs = obs, so it now copies the index as it came off assign() rather than after AnnData's obs setter has coerced it. No effect for an index read from .h5ad, but INSTANCE_KEY is the join key against the shapes element.
  • merscope: _get_reader is annotated Callable[..., Image2DModel], but both loaders return what Image2DModel.parse() returns (DataArray/DataTree).
  • Coverage: nine end-to-end reader tests are gated behind @skip_if_below_python_version() with MIN_VERSION = (3, 13) (test_xenium.py, test_visium_hd.py, test_seqfish.py), while the hatch matrix is 3.12 + 3.14 — so on the 3.12 leg they are all skipped. The gate predates Adopt the current scverse cookiecutter template #411; if it only exists for tests/_utils.py's own typing it can probably be dropped now that the floor is 3.12.

Also noticed nearby (pre-existing, not from #411)

  • curio: var.join(var_features_moransi, how="outer") discards its return value and, unlike obs, the local var is never assigned back to adata.var — the Moran's I columns never reach the object.
  • macsima: create_sdata()'s physical-size loop has no break, so the last successfully parsed file wins despite the "Trying next file" message.
  • codex: if path_files and CodexKeys.FCS_FILE or CodexKeys.FCS_FILE_CSV in patt.pattern: — the second operand of or is a non-empty enum member, so the condition is always true, the else: raise ValueError("Cannot determine data set...") is dead, and an empty path_files gives IndexError instead of that message. Also pd.read_csv(path_files[0], ...) and imread(path_files[0], ...) are missing the path / prefix, so the .csv and .tif branches only work when cwd happens to be path. codex has no tests.
  • dbit: adata.obs["region"] = ... writes to the view produced by adata = adata[idx].

AI-generated: this review, its reproductions and the accompanying PR were produced by Claude Opus 5 (Claude Code). Every failure described above was reproduced locally against main; the wording is the model's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions