Skip to content

xnano.utils.validation

xnano.utils.validation

xnano.utils.validation


Validate fields, command parameters, and component values.

Functions:

infer_pydantic_core_schema_name cached

infer_pydantic_core_schema_name(annotation: type) -> str

Infers the pydantic_core schema name for a given type annotation.

Parameters:

  • annotation (type) –

    The type to infer the schema name for.

Returns:

  • str

    The pydantic_core schema name string for the given type.

Source code in xnano/utils/validation.py
@functools.lru_cache(maxsize=1024)
def infer_pydantic_core_schema_name(annotation: type) -> str:
    """Infers the ``pydantic_core`` schema name for a given type annotation.

    Args:
        annotation: The type to infer the schema name for.

    Returns:
        The ``pydantic_core`` schema name string for the given type.
    """
    origin = get_origin(annotation)
    if _is_union_origin(origin):
        args = get_args(annotation)
        if type(None) in args:
            return "nullable"
        return "union"

    _ORIGIN_MAP: dict = {
        list: "list",
        tuple: "tuple",
        set: "set",
        frozenset: "frozenset",
        dict: "dict",
        Generator: "generator",
    }
    if origin in _ORIGIN_MAP:
        return _ORIGIN_MAP[origin]

    _TYPE_MAP: dict[type, str] = {
        bool: "bool",
        bytes: "bytes",
        float: "float",
        int: "int",
        str: "str",
        complex: "complex",
        datetime.date: "date",
        datetime.time: "time",
        datetime.datetime: "datetime",
        datetime.timedelta: "timedelta",
        uuid.UUID: "uuid",
    }
    if annotation in _TYPE_MAP:
        return _TYPE_MAP[annotation]

    if inspect.isclass(annotation):
        if issubclass(annotation, enum.Enum):
            return "enum"
        if dataclasses.is_dataclass(annotation):
            return "dataclass"
        if hasattr(annotation, "model_fields"):
            return "pydantic-model"

    return "is-instance"

layout_field_annotation

layout_field_annotation() -> Any

Default type annotation for layout fields without an explicit one.

Source code in xnano/utils/validation.py
def layout_field_annotation() -> Any:
    """Default type annotation for layout fields without an explicit one."""
    return _get_renderable_annotation()

register_validatable_type

register_validatable_type(
    annotation: Any,
) -> SchemaValidator

Builds and caches a SchemaValidator for a type annotation.

Supports primitives, stdlib types, generic containers, Literal, Union, enums, TypedDict, dataclasses, and pydantic models. Falls back to an isinstance check for unrecognised types.

Parameters:

  • annotation (Any) –

    The type annotation to build a validator for.

Returns:

  • SchemaValidator

    A cached SchemaValidator for the given annotation.

Source code in xnano/utils/validation.py
def register_validatable_type(annotation: Any) -> SchemaValidator:
    """Builds and caches a ``SchemaValidator`` for a type annotation.

    Supports primitives, stdlib types, generic containers, ``Literal``,
    ``Union``, enums, ``TypedDict``, dataclasses, and pydantic models.
    Falls back to an isinstance check for unrecognised types.

    Args:
        annotation: The type annotation to build a validator for.

    Returns:
        A cached ``SchemaValidator`` for the given annotation.
    """
    try:
        if annotation not in _SCHEMA_VALIDATOR_CACHE:
            _SCHEMA_VALIDATOR_CACHE[annotation] = SchemaValidator(
                schema=_build_core_schema(annotation)
            )
        return _SCHEMA_VALIDATOR_CACHE[annotation]
    except TypeError:
        return SchemaValidator(schema=_build_core_schema(annotation))

validate_type

validate_type(value: Any, annotation: Any) -> Any

Validates a value against a type annotation using pydantic_core.

Parameters:

  • value (Any) –

    The value to validate.

  • annotation (Any) –

    The type annotation to validate against.

Returns:

  • Any

    The validated (and coerced, where applicable) value.

Raises:

  • ValidationError

    If value does not satisfy annotation.

Source code in xnano/utils/validation.py
def validate_type(value: Any, annotation: Any) -> Any:
    """Validates a value against a type annotation using ``pydantic_core``.

    Args:
        value: The value to validate.
        annotation: The type annotation to validate against.

    Returns:
        The validated (and coerced, where applicable) value.

    Raises:
        ValidationError: If ``value`` does not satisfy ``annotation``.
    """
    return register_validatable_type(annotation).validate_python(value)