diff --git a/ccflow/callable.py b/ccflow/callable.py index 4cd3ec04..6df76545 100644 --- a/ccflow/callable.py +++ b/ccflow/callable.py @@ -951,7 +951,7 @@ def _validate_callable_model_generic_type(cls, m, handler, info): # Raise ValueError (not TypeError) as per https://docs.pydantic.dev/latest/errors/errors/ if not isinstance(m, CallableModel): - raise ValueError(f"{m} is not a CallableModel: {type(m)}") # noqa: TRY004 + raise ValueError("Expected a CallableModel") # noqa: TRY004 subtypes = cls.__pydantic_generic_metadata__["args"] if subtypes: diff --git a/ccflow/enums.py b/ccflow/enums.py index 3cc1a1d0..aebcc75f 100644 --- a/ccflow/enums.py +++ b/ccflow/enums.py @@ -120,7 +120,7 @@ def validate(cls, v) -> "Enum": raise ValueError(f"Cannot convert value to {cls.__name__}: {v}") from e elif isinstance(v, int): return cls(v) - raise ValueError(f"Cannot convert value to enum: {v}") + raise ValueError(f"Cannot convert value to {cls.__name__}") @staticmethod def _serialize(value: "Enum") -> str: diff --git a/ccflow/exttypes/arrow.py b/ccflow/exttypes/arrow.py index 9f2f3765..7f701f65 100644 --- a/ccflow/exttypes/arrow.py +++ b/ccflow/exttypes/arrow.py @@ -51,7 +51,7 @@ def _validate(cls, value: Any) -> Self: if isinstance(value, pa.Schema): return ArrowSchema.make(value) - raise ValueError(f"Cannot convert value to ArrowSchema, expects ArrowSchema or pa.Schema: {value}") + raise ValueError("Cannot convert value to ArrowSchema, expects ArrowSchema or pa.Schema") @classmethod def validate(cls, value: Any) -> Self: @@ -89,7 +89,7 @@ def _validate(cls, v, schema, strict): except TypeError: pass if not isinstance(v, pa.Table): - raise ValueError(f"Value of type {type(v)} cannot be converted to pyarrow.Table") # noqa: TRY004 + raise ValueError("Value cannot be converted to pyarrow.Table") # noqa: TRY004 if schema: if strict is True: @@ -134,7 +134,7 @@ def _validate(cls, value) -> Self: _ = value.datatype return value - raise ValueError(f"ensure this value contains a valid PyarrowDatatype string: {value}") + raise ValueError("ensure this value contains a valid PyarrowDatatype string") @classmethod def validate(cls, value) -> Self: diff --git a/ccflow/exttypes/exprtk.py b/ccflow/exttypes/exprtk.py index 040bb54b..667082b9 100644 --- a/ccflow/exttypes/exprtk.py +++ b/ccflow/exttypes/exprtk.py @@ -37,7 +37,7 @@ def _validate(cls, value: Any) -> Self: return cls(value) - raise ValueError(f"{value} cannot be converted into an ExprTkExpression.") + raise ValueError("Value cannot be converted into an ExprTkExpression.") @classmethod def validate(cls, value: Any) -> Self: diff --git a/ccflow/exttypes/narwhals.py b/ccflow/exttypes/narwhals.py index 2a13a212..0d6579c5 100644 --- a/ccflow/exttypes/narwhals.py +++ b/ccflow/exttypes/narwhals.py @@ -86,7 +86,7 @@ def validate_from_any(value: Any): if cls.lazy is False and isinstance(value, nw.LazyFrame): value = value.collect() if cls.lazy is None and not isinstance(value, source_origin): - raise ValueError(f"Expected {source_origin} but got {type(value)}") + raise ValueError(f"Expected {source_origin}") try: source_arg_adapter.validate_python(value.to_native()) @@ -156,14 +156,14 @@ def validate_from_any(value: Any): if inspect.isclass(value) and issubclass(value, nw.dtypes.DType): value = value() if not isinstance(value, nw.dtypes.DType): - raise ValueError(f"Expected a Narwhals DType but got {type(value)}") # noqa: TRY004 + raise ValueError("Expected a Narwhals DType") # noqa: TRY004 return value def serialize(value: Any): if inspect.isclass(value) and issubclass(value, nw.dtypes.DType): value = value() if not isinstance(value, nw.dtypes.DType): - raise ValueError(f"Expected a Narwhals DType but got {type(value)}") # noqa: TRY004 + raise ValueError("Expected a Narwhals DType") # noqa: TRY004 return str(value) from_any_schema = core_schema.no_info_plain_validator_function(validate_from_any) @@ -199,7 +199,7 @@ def __post_init__(self): def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: def validate_schema(value: Any): if not isinstance(value, (nw.DataFrame, nw.LazyFrame)): - raise ValueError(f"Expected a Narwhals DataFrame or LazyFrame but got {type(value)}") # noqa: TRY004 + raise ValueError("Expected a Narwhals DataFrame or LazyFrame") # noqa: TRY004 schema = value.collect_schema() if self.allow_subset: schema = nw.Schema({k: v for k, v in schema.items() if k in self.schema}) diff --git a/ccflow/exttypes/polars.py b/ccflow/exttypes/polars.py index d909c256..d328a3cf 100644 --- a/ccflow/exttypes/polars.py +++ b/ccflow/exttypes/polars.py @@ -74,7 +74,7 @@ def _validate(cls, value: Any) -> Self: raise ValueError(f"Supplied value '{value}' does not evaluate to a Polars expression") # noqa: TRY004 return cls._coerce_from_expr(expression) - raise ValueError(f"Supplied value '{value}' cannot be converted to a Polars expression") + raise ValueError("Cannot convert value to a Polars expression") class _PolarsSelectorPydanticAnnotation(_PolarsExprPydanticAnnotation): diff --git a/ccflow/exttypes/pydantic_numpy/ndarray.py b/ccflow/exttypes/pydantic_numpy/ndarray.py index cd3608e5..868d6bf5 100644 --- a/ccflow/exttypes/pydantic_numpy/ndarray.py +++ b/ccflow/exttypes/pydantic_numpy/ndarray.py @@ -59,7 +59,7 @@ def _validate(v): return np.asarray(v) except TypeError: - raise ValueError(f"Unable to convert {v} to an array.") + raise ValueError("Unable to convert value to an array.") return core_schema.no_info_before_validator_function( _validate, diff --git a/ccflow/exttypes/pyobjectpath.py b/ccflow/exttypes/pyobjectpath.py index cb17b63d..1d38c402 100644 --- a/ccflow/exttypes/pyobjectpath.py +++ b/ccflow/exttypes/pyobjectpath.py @@ -134,7 +134,7 @@ def _path_from_object(cls, value: Any) -> "PyObjectPath": if hasattr(value, "__module__") and hasattr(value, "__qualname__"): return cls(_build_standard_import_path(value)) - raise ValueError(f"ensure this value contains valid import path or importable object: unable to import path for {value}") + raise ValueError("ensure this value contains valid import path or importable object") @classmethod @cache diff --git a/ccflow/publishers/file.py b/ccflow/publishers/file.py index 333f96a3..2c626843 100644 --- a/ccflow/publishers/file.py +++ b/ccflow/publishers/file.py @@ -189,7 +189,7 @@ class PandasFilePublisher(BasePublisher): def _check_data(cls, v): pd = sys.modules.get("pandas") # a DataFrame cannot exist unless pandas is already imported if v is not None and (pd is None or not isinstance(v, pd.DataFrame)): - raise ValueError(f"data must be a pandas DataFrame, not {type(v).__name__}") + raise ValueError("data must be a pandas DataFrame") return v @override diff --git a/ccflow/tests/test_callable.py b/ccflow/tests/test_callable.py index 36802137..f8c97df1 100644 --- a/ccflow/tests/test_callable.py +++ b/ccflow/tests/test_callable.py @@ -1,10 +1,11 @@ from pickle import dumps as pdumps, loads as ploads from typing import Generic, TypeVar from unittest import TestCase +from unittest.mock import Mock, patch import cloudpickle import ray -from pydantic import Field, ValidationError +from pydantic import BaseModel, Field, ValidationError from ray.cloudpickle import dumps as rcpdumps, loads as rcploads from ccflow import ( @@ -246,6 +247,12 @@ def __call__(self, context): return self.model(context) +class UnionBranchHost(BaseModel): + """Host with a ``CallableModelGenericType[Ctx, R] | R`` union field.""" + + field: CallableModelGenericType[MyContext, MyResult] | MyResult + + class MyTest(ContextBase): c: MyContext @@ -599,6 +606,19 @@ def test_wrapper_reference(self): self.assertEqual(w.context_type, m.context_type) self.assertEqual(w.result_type, m.result_type) + def test_union_rejection_does_not_format_value(self): + # When a union has a generic-callable branch, pydantic still attempts that branch for a + # plain-model value. The wrap validator must reject it without stringifying the value. + inst = MyResult(x=1, y="a") + str_mock = Mock(return_value="") + repr_mock = Mock(return_value="") + with patch.object(MyResult, "__str__", str_mock), patch.object(MyResult, "__repr__", repr_mock): + host = UnionBranchHost(field=inst) + str_mock.assert_not_called() + repr_mock.assert_not_called() + self.assertIsInstance(host.field, MyResult) + self.assertEqual(host.field.x, 1) + def test_use_as_base_class(self): class MyCallable(CallableModelGenericType[NullContext, GenericResult[int]]): @Flow.call