|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | | -from collections.abc import Hashable, Iterable, Sequence |
| 5 | +import functools |
| 6 | +import inspect |
| 7 | +from collections.abc import Callable, Hashable, Iterable, Sequence |
6 | 8 | from contextlib import contextmanager |
7 | 9 | from typing import Any |
8 | 10 |
|
|
14 | 16 | from pandas.api.types import infer_dtype |
15 | 17 | from scanpy import logging as logg |
16 | 18 | from scipy.sparse import csc_matrix, csr_matrix, spmatrix |
| 19 | +from spatialdata import SpatialData |
17 | 20 |
|
18 | 21 | from squidpy._compat import ArrayView, SparseCSCView, SparseCSRView |
19 | 22 | from squidpy._docs import d |
20 | 23 | from squidpy._utils import NDArrayA, _unique_order_preserving |
21 | 24 |
|
22 | 25 |
|
| 26 | +_TABLE_KEY_DOC = """ table_key |
| 27 | + Key in :attr:`spatialdata.SpatialData.tables` where the table is stored. |
| 28 | + Only used if ``adata`` is a :class:`spatialdata.SpatialData`.""" |
| 29 | + |
| 30 | + |
| 31 | +def extract_table_if_spatialdata(fn: Callable[..., Any]) -> Callable[..., Any]: |
| 32 | + """Decorator that resolves a :class:`~spatialdata.SpatialData` to an :class:`~anndata.AnnData`. |
| 33 | +
|
| 34 | + Adds a ``table_key`` parameter (default ``"table"``) to the wrapped |
| 35 | + function's signature **and** appends its documentation to the docstring. |
| 36 | + When the first positional argument (``adata``) is a |
| 37 | + :class:`~spatialdata.SpatialData`, the table is looked up via |
| 38 | + ``adata.tables[table_key]`` and passed through in its place. |
| 39 | + """ |
| 40 | + sig = inspect.signature(fn) |
| 41 | + |
| 42 | + table_param = inspect.Parameter( |
| 43 | + "table_key", |
| 44 | + inspect.Parameter.KEYWORD_ONLY, |
| 45 | + default="table", |
| 46 | + ) |
| 47 | + params = list(sig.parameters.values()) |
| 48 | + kw_only_start = next( |
| 49 | + (i for i, p in enumerate(params) if p.kind == inspect.Parameter.KEYWORD_ONLY), |
| 50 | + len(params), |
| 51 | + ) |
| 52 | + var_kw = [i for i, p in enumerate(params) if p.kind == inspect.Parameter.VAR_KEYWORD] |
| 53 | + insert_pos = var_kw[0] if var_kw else kw_only_start |
| 54 | + params.insert(insert_pos, table_param) |
| 55 | + new_sig = sig.replace(parameters=params) |
| 56 | + |
| 57 | + @functools.wraps(fn) |
| 58 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 59 | + bound = new_sig.bind(*args, **kwargs) |
| 60 | + bound.apply_defaults() |
| 61 | + table_key: str = bound.arguments.pop("table_key") |
| 62 | + |
| 63 | + adata = bound.arguments.get("adata") |
| 64 | + if isinstance(adata, SpatialData): |
| 65 | + if table_key not in adata.tables: |
| 66 | + raise ValueError( |
| 67 | + f"Table {table_key!r} not found in SpatialData. " |
| 68 | + f"Available tables: {list(adata.tables.keys())}" |
| 69 | + ) |
| 70 | + bound.arguments["adata"] = adata.tables[table_key] |
| 71 | + |
| 72 | + return fn(*bound.args, **bound.kwargs) |
| 73 | + |
| 74 | + wrapper.__signature__ = new_sig # type: ignore[attr-defined] |
| 75 | + |
| 76 | + if wrapper.__doc__ is not None: |
| 77 | + # Insert table_key docs before the "Returns" / "Notes" / "References" |
| 78 | + # section, or append at the end of Parameters if none found. |
| 79 | + doc = wrapper.__doc__ |
| 80 | + for marker in ("Returns\n", "Notes\n", "References\n"): |
| 81 | + idx = doc.find(marker) |
| 82 | + if idx != -1: |
| 83 | + # Back up past the " -------\n" underline to the section header |
| 84 | + header_start = doc.rfind("\n", 0, idx - 1) |
| 85 | + doc = doc[:header_start] + "\n" + _TABLE_KEY_DOC + "\n" + doc[header_start:] |
| 86 | + break |
| 87 | + else: |
| 88 | + doc = doc.rstrip() + "\n" + _TABLE_KEY_DOC + "\n" |
| 89 | + wrapper.__doc__ = doc |
| 90 | + |
| 91 | + return wrapper |
| 92 | + |
| 93 | + |
23 | 94 | def _check_tuple_needles( |
24 | 95 | needles: Sequence[tuple[Any, Any]], |
25 | 96 | haystack: Sequence[Any], |
|
0 commit comments