Skip to content

don’t return dicts #17

Closed

Description

@flying-sheep

e.g pp.filter_genes_dispersion returns a dict with known keys. if you know the keys, this means you should return an object where you can use attribute access instead. usually the pythonic thing to do in this case is to return a namedtuple.

in this case though, we have

>>> {k: v.shape for k, v in filter_result.items()}
{'dispersions': (173351,),
 'dispersions_norm': (173351,),
 'gene_filter': (173351,),
 'means': (173351,)}

which is a perfect case for a recarray.

Activity

  1. flying-sheep commented on Sep 11, 2026

    @flying-sheep
    MemberAuthor

    funnily we haven’t quite fixed this: normalize_total still returns a dict. Can be fixed like this maybe:

    from __future__ import annotations
    
    from collections.abc import Mapping
    from dataclasses import fields, is_dataclass
    from typing import TYPE_CHECKING
    
    from scverse_misc import Deprecation, deprecated
    
    if TYPE_CHECKING:
        from collections.abc import Iterator
        from typing import Final
    
    
    __all__ = ["DeprecatedMapping"]
    
    MSG: Final = Deprecation(
        "1.13.0",
        "Indexing this result like a `dict` is deprecated. Access its attributes instead.",
    )
    
    
    class DeprecatedMapping[V](Mapping[str, V]):
        """`Mapping` interface over a dataclass’ fields, for types that used to be `dict`s."""
    
        @deprecated(MSG)
        def __getitem__(self, key: str) -> V:
            assert is_dataclass(self)
            if key not in (names := [f.name for f in fields(self)]):
                msg = f"{key!r}, expected one of {names}"
                raise KeyError(msg)
            return getattr(self, key)
    
        @deprecated(MSG)
        def __iter__(self) -> Iterator[str]:
            assert is_dataclass(self)
            return (f.name for f in fields(self))
    
        @deprecated(MSG)
        def __len__(self) -> int:
            assert is_dataclass(self)
            return len(fields(self))
    from dataclasses import dataclass
    from typing import TYPE_CHECKING
    
    from .._utils import DeprecatedMapping
    
    if TYPE_CHECKING:
        import numpy as np
    
        from .._compat import CSBase, DaskArray
    
    
    @dataclass(frozen=True)
    class NormalizedTotal(DeprecatedMapping["np.ndarray | CSBase | DaskArray"]):
        """Result of :func:`~scanpy.pp.normalize_total`."""
    
        X: np.ndarray | CSBase | DaskArray
        """The normalized matrix."""
        norm_factor: np.ndarray | DaskArray
        """Counts per cell before normalization."""
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

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions