Skip to content

Commit

Permalink
Update attrs usage based on PR feedback
Browse files Browse the repository at this point in the history
- Add docstrings to Axis
- Use `attrs` for CoordinateSpace
- Add helper function for validation
  • Loading branch information
jp-dark committed Sep 17, 2024
1 parent 0b63287 commit 99d5df2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 34 deletions.
51 changes: 18 additions & 33 deletions python-spec/src/somacore/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,23 @@
import numpy as np
import numpy.typing as npt

from .types import to_string_tuple


@attrs.define(frozen=True)
class Axis:
"""A description of an axis of a coordinate system
Args:
name: Name of the axis.
unit: Optional units. Defaults to ``None``.
Lifecycle: experimental
"""

name: str
"""Name of the axis."""
unit: Optional[str] = None
"""Optional string name for the units of the axis."""


@attrs.define(frozen=True)
class CoordinateSpace(collections.abc.Sequence):
"""A coordinate space for spatial data.
Expand All @@ -33,40 +34,28 @@ class CoordinateSpace(collections.abc.Sequence):
Lifecycle: experimental
"""

def __init__(self, axes: Sequence[Axis]):
self._axes = tuple(axes)
if len(self._axes) == 0:
raise ValueError("Coordinate space must have at least one axis.")
if len(set(axis.name for axis in self._axes)) != len(axes):
raise ValueError("The names for the axes must be unique.")
axes: Tuple[Axis, ...] = attrs.field(converter=tuple)

@axes.validator
def _validate(self, _, axes: Tuple[Axis, ...]) -> None:
if not axes:
raise ValueError("at least one")
if len(set(axis.name for axis in self.axes)) != len(axes):
raise ValueError("unique")

def __len__(self) -> int:
return len(self._axes)
return len(self.axes)

def __getitem__(self, index: int) -> Axis: # type: ignore[override]
return self._axes[index]

def __repr__(self) -> str:
output = f"<{type(self).__name__}\n"
for axis in self._axes:
output += f" {axis},\n"
return output + ">"

@property
def axes(self) -> Tuple[Axis, ...]:
"""The axes in the coordinate space.
Lifecycle: experimental
"""
return self._axes
return self.axes[index]

@property
def axis_names(self) -> Tuple[str, ...]:
"""The names of the axes in order.
Lifecycle: experimental
"""
return tuple(axis.name for axis in self._axes)
return tuple(axis.name for axis in self.axes)


class CoordinateTransform(metaclass=abc.ABCMeta):
Expand All @@ -86,12 +75,8 @@ def __init__(
input_axes: Union[str, Sequence[str]],
output_axes: Union[str, Sequence[str]],
):
self._input_axes = (
(input_axes,) if isinstance(input_axes, str) else tuple(input_axes)
)
self._output_axes = (
(output_axes,) if isinstance(output_axes, str) else tuple(output_axes)
)
self._input_axes = to_string_tuple(input_axes)
self._output_axes = to_string_tuple(output_axes)

@abc.abstractmethod
def __matmul__(self, other: "CoordinateTransform") -> "CoordinateTransform":
Expand Down
21 changes: 20 additions & 1 deletion python-spec/src/somacore/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,16 @@

import sys
from concurrent import futures
from typing import TYPE_CHECKING, NoReturn, Optional, Sequence, Type, TypeVar
from typing import (
TYPE_CHECKING,
NoReturn,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)

from typing_extensions import Protocol, TypeGuard

Expand All @@ -22,6 +31,16 @@ def is_nonstringy_sequence(it: object) -> TypeGuard[Sequence]:
return not isinstance(it, (str, bytes)) and isinstance(it, Sequence)


def to_string_tuple(obj: Union[str, Sequence[str]]) -> Tuple[str, ...]:
"""Returns a tuple of string values.
If the input is a string, it is returned as a tuple with the sting as its
only item. If it is otherwise a sequence of strings, the sequence is converted
to a tuple.
"""
return (obj,) if isinstance(obj, str) else tuple(obj)


_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)

Expand Down

0 comments on commit 99d5df2

Please sign in to comment.