From 68f3f8b72b78583ea2c70b1872fab5d27d4fa6cb Mon Sep 17 00:00:00 2001 From: Nathaniel Starkman Date: Wed, 17 Jul 2024 14:50:24 -0400 Subject: [PATCH] feat(space): set precedence on dispatches (#139) Signed-off-by: nstarman --- conftest.py | 2 -- src/coordinax/_space.py | 32 ++++++++++++++++++++------------ 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/conftest.py b/conftest.py index fc6f007..3a90441 100644 --- a/conftest.py +++ b/conftest.py @@ -1,7 +1,5 @@ """Doctest configuration.""" -from __future__ import annotations - from doctest import ELLIPSIS, NORMALIZE_WHITESPACE from sybil import Sybil diff --git a/src/coordinax/_space.py b/src/coordinax/_space.py index 7901f96..2c78b24 100644 --- a/src/coordinax/_space.py +++ b/src/coordinax/_space.py @@ -451,6 +451,10 @@ def to_units( raise NotImplementedError +# =============================================================== +# Related dispatches + + @dispatch # type: ignore[misc] def represent_as(space: Space, target: type[AbstractVector], /) -> Space: """Represent the current vector to the target vector.""" @@ -459,6 +463,22 @@ def represent_as(space: Space, target: type[AbstractVector], /) -> Space: ) +# NOTE: need to set the precedence because `Space` is both a `Mapping` and a +# `dataclass`, which are both in the `replace` dispatch table. +@dispatch(precedence=1) # type: ignore[misc] +def replace(obj: Space, /, **kwargs: AbstractVector) -> Space: + """Replace the components of the vector.""" + return type(obj)(**{**obj, **kwargs}) + + +# NOTE: need to set the precedence because `Space` is both a `Mapping` and a +# `dataclass`, which are both in the `field_items` dispatch table. +@dispatch(precedence=1) # type: ignore[misc] +def field_items(obj: Space, /) -> ItemsView[str, AbstractVector]: + """Return the items from a Space.""" + return obj.items() + + # =============================================================== Temporary # These functions are very similar to `represent_as`, but I don't think this is # the best API. Until we figure out a better way to do this, we'll keep these @@ -495,15 +515,3 @@ def temp_represent_as( space["speed"], space["length"], ) - - -@dispatch # type: ignore[misc] -def replace(obj: Space, /, **kwargs: AbstractVector) -> Space: - """Replace the components of the vector.""" - return type(obj)(**{**obj, **kwargs}) - - -@dispatch # type: ignore[misc] -def field_items(obj: Space, /) -> ItemsView[str, AbstractVector]: - """Return the items from a Space.""" - return obj.items()