|
26 | 26 | if TYPE_CHECKING: |
27 | 27 | from zarr.core.common import JSON |
28 | 28 |
|
29 | | -__all__ = ["MAX_JSON_DEPTH", "convert", "validate_json_value"] |
| 29 | +__all__ = ["MAX_JSON_DEPTH", "convert", "parse_field", "validate_json_value"] |
30 | 30 |
|
31 | 31 | MAX_JSON_DEPTH: Final = 64 |
32 | 32 | """Maximum nesting depth accepted by :func:`validate_json_value`.""" |
33 | 33 |
|
34 | 34 |
|
| 35 | +def _type_name(type_: Any) -> str: |
| 36 | + return getattr(type_, "__name__", None) or str(type_).replace("typing.", "") |
| 37 | + |
| 38 | + |
35 | 39 | def convert(value: object, type_: Any, *, strict: bool = True) -> Any: |
36 | 40 | """Validate and coerce ``value`` against ``type_`` via :func:`msgspec.convert`. |
37 | 41 |
|
38 | | - msgspec handles the JSON-shaped coercions Zarr needs but raises |
39 | | - :class:`msgspec.ValidationError` on a mismatch. We translate that to |
40 | | - ``TypeError`` so callers can keep raising the exception types the rest of |
41 | | - Zarr already expects. |
| 42 | + On a mismatch msgspec raises :class:`msgspec.ValidationError`; this re-raises |
| 43 | + a plain, field-agnostic ``ValueError`` naming the expected type, so callers |
| 44 | + can add their own field context (see :func:`parse_field`). |
42 | 45 | """ |
43 | 46 | try: |
44 | 47 | return msgspec.convert(value, type_, strict=strict) |
45 | 48 | except msgspec.ValidationError as exc: |
46 | | - raise TypeError(str(exc)) from exc |
| 49 | + raise ValueError(f"Expected instance of {_type_name(type_)}, got {value!r}.") from exc |
| 50 | + |
| 51 | + |
| 52 | +def parse_field( |
| 53 | + data: object, type_: Any, field: str, *, error: type[Exception] = ValueError |
| 54 | +) -> Any: |
| 55 | + """Validate ``data`` for metadata field ``field`` against ``type_``. |
| 56 | +
|
| 57 | + Wraps :func:`convert` and, on failure, re-raises ``error`` with field |
| 58 | + context, chaining the underlying type error. This keeps the |
| 59 | + ``convert``-then-re-raise pattern in one place rather than repeating it in |
| 60 | + every per-field parser. |
| 61 | + """ |
| 62 | + try: |
| 63 | + return convert(data, type_) |
| 64 | + except ValueError as exc: |
| 65 | + raise error(f"Failed to parse input for {field!r}.") from exc |
47 | 66 |
|
48 | 67 |
|
49 | 68 | def validate_json_value(value: object, *, max_depth: int = MAX_JSON_DEPTH, _depth: int = 0) -> JSON: |
|
0 commit comments