From 5d4b0e2942e5a9ddd41309bcf6a180a58d6ae637 Mon Sep 17 00:00:00 2001 From: Matthew Smith Date: Thu, 9 Jan 2025 15:20:21 -0600 Subject: [PATCH] remove map_foreign from Mapper --- pytato/stringifier.py | 7 +++++-- pytato/transform/__init__.py | 19 +++++++++---------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/pytato/stringifier.py b/pytato/stringifier.py index 952b8f8e2..17c915778 100644 --- a/pytato/stringifier.py +++ b/pytato/stringifier.py @@ -39,7 +39,7 @@ IndexLambda, ReductionDescriptor, ) -from pytato.transform import Mapper +from pytato.transform import ForeignObjectError, Mapper if TYPE_CHECKING: @@ -77,7 +77,10 @@ def rec(self, expr: Any, depth: int) -> str: try: return self._cache[cache_key] except KeyError: - result = super().rec(expr, depth) + try: + result = super().rec(expr, depth) + except ForeignObjectError: + result = self.map_foreign(expr, depth) self._cache[cache_key] = result return result diff --git a/pytato/transform/__init__.py b/pytato/transform/__init__.py index 1796d62c0..65e136dcc 100644 --- a/pytato/transform/__init__.py +++ b/pytato/transform/__init__.py @@ -161,6 +161,10 @@ class UnsupportedArrayError(ValueError): pass +class ForeignObjectError(ValueError): + pass + + # {{{ mapper base class ResultT = TypeVar("ResultT") @@ -185,7 +189,6 @@ class Mapper(Generic[ResultT, FunctionResultT, P]): if this is not desired. .. automethod:: handle_unsupported_array - .. automethod:: map_foreign .. automethod:: rec .. automethod:: __call__ """ @@ -199,13 +202,6 @@ def handle_unsupported_array(self, expr: MappedT, raise UnsupportedArrayError( f"{type(self).__name__} cannot handle expressions of type {type(expr)}") - def map_foreign(self, expr: Any, *args: P.args, **kwargs: P.kwargs) -> Any: - """Mapper method that is invoked for an object of class for which a - mapper method does not exist in this mapper. - """ - raise ValueError( - f"{type(self).__name__} encountered invalid foreign object: {expr!r}") - def rec(self, expr: ArrayOrNames, *args: P.args, **kwargs: P.kwargs) -> ResultT: """Call the mapper method of *expr* and return the result.""" method: Callable[..., Any] | None @@ -223,7 +219,9 @@ def rec(self, expr: ArrayOrNames, *args: P.args, **kwargs: P.kwargs) -> ResultT: else: return self.handle_unsupported_array(expr, *args, **kwargs) else: - return cast("ResultT", self.map_foreign(expr, *args, **kwargs)) + raise ForeignObjectError( + f"{type(self).__name__} encountered invalid foreign " + f"object: {expr!r}") from None assert method is not None return cast("ResultT", method(expr, *args, **kwargs)) @@ -237,7 +235,8 @@ def rec_function_definition( try: method = self.map_function_definition # type: ignore[attr-defined] except AttributeError: - return cast("FunctionResultT", self.map_foreign(expr, *args, **kwargs)) + raise ValueError( + f"{type(self).__name__} lacks a mapper method for functions.") from None assert method is not None return cast("FunctionResultT", method(expr, *args, **kwargs))