Skip to content

verify

Class info

🛈 DocStrings

verify_type

verify_type(data: Any, type_hint: type[T]) -> T

Verify that data matches the expected type using pydantic.

Parameters:

Name Type Description Default
data Any

Data to verify

required
type_hint type[T]

Type to verify against (including TypedDict)

required

Returns:

Type Description
T

The validated data

Raises:

Type Description
TypeError

If validation fails

Source code in src/configz/verify.py
def verify_type[T](data: Any, type_hint: type[T]) -> T:
    """Verify that data matches the expected type using pydantic.

    Args:
        data: Data to verify
        type_hint: Type to verify against (including TypedDict)

    Returns:
        The validated data

    Raises:
        TypeError: If validation fails
    """
    if isinstance(type_hint, type) and not hasattr(type_hint, "__annotations__"):  # pyright: ignores
        if isinstance(data, type_hint):
            return data
        msg = f"Expected {type_hint.__name__}, got {type(data).__name__}"
        raise TypeError(msg)

    # Use pydantic for complex types
    try:
        from pydantic import TypeAdapter

        adapter = TypeAdapter(type_hint)
        return adapter.validate_python(data)
    except Exception as e:
        msg = f"Data doesn't match type {type_hint.__name__}: {e}"
        raise TypeError(msg) from e