Skip to content

yggdrasil.data.cast

cast

identity

identity(x: Any, *args, **kwargs) -> Any

Return value as-is.

register_converter

register_converter(from_hint: Any, to_hint: Any) -> Callable[[F], F]

Decorator to register a converter from from_hint -> to_hint.

This preserves the original function object (and its type signature), while registering it as a runtime Converter.

Wildcard registrations

If from_hint is typing.Any or object, the converter is stored in _any_registry[to_hint] and is eligible for any source value type.

Expected converter behavior

func(value, options) -> converted_value

where options may be None.

convert

convert(
    value: Any,
    target_hint: type[T],
    options: Optional[Union["CastOptions", Field, DataType, Schema]] = None,
    **kwargs: Any
) -> T

Convert value to target_hint using registered converters + built-ins.

Dispatch order (cheapest first): 1) Any / object target → identity passthrough. 2) Plain-type identity: isinstance(value, target_hint) → identity. Most calls (convert(42, int), convert('x', str)) bail out here, before any function call. 3) Optional[T] unwrap for generic-alias targets. 4) NoneNone if optional, else default_scalar(target). 5) Registry lookup (exact / wildcard / namespace / MRO / scan-fallback). 6) Enum member resolution and dataclass from-mapping coercion. 7) Container generics — list / set / tuple / dict / Mapping. 8) TypeError — no path found.

Options are normalized through CastOptions.check only when the caller actually supplied one (the no-options call site, which is the overwhelmingly common one, skips the allocation and the import).

truncate_datetime

truncate_datetime(
    value: Any,
    interval: str | timedelta,
    tz: str | tzinfo | timedelta | None = None,
    add_interval: bool = False,
) -> dt.datetime

Truncate a datetime-like value to the boundary defined by interval.

Supported interval examples
  • dt.timedelta(seconds=15)
  • dt.timedelta(minutes=5)
  • dt.timedelta(hours=4)
  • dt.timedelta(days=7)
  • "PT15S", "PT15M", "PT4H"
  • "P1D", "P1W", "P1M", "P3M", "P1Y"
Rules
  • timedelta and fixed-width ISO intervals truncate from Unix epoch.
  • Calendar intervals (months/years) truncate from calendar boundaries.
  • If add_interval=True and value is not already aligned, return the next boundary.

iter_datetime_ranges

iter_datetime_ranges(
    start: Any,
    end: Any,
    interval: str | timedelta,
    tz: str | tzinfo | timedelta | None = None,
) -> Iterator[tuple[dt.datetime, dt.datetime]]

Iterate over aligned datetime ranges between start and end.

Supported interval examples
  • dt.timedelta(seconds=30)
  • dt.timedelta(minutes=15)
  • dt.timedelta(hours=4)
  • dt.timedelta(days=1)
  • "PT1S", "PT30S"
  • "PT1M", "PT15M"
  • "PT1H", "PT4H"
  • "P1D", "P7D"
  • "P1W"
  • "P1M", "P3M"
  • "P1Y"