Skip to content

Pydantic Extensions

Enhanced features for Pydantic models.


xpytools.xtool.xpyt_pydantic.TypeSafeAccessMixin.TypeSafeAccessMixin

Adds safe pre-validation coercion and uniform attribute serialization for Pydantic models.

Place this before BaseModel in the inheritance list to ensure its validator runs first.

Methods:

Name Description
get_all_type_safe_attr

Return all attributes in JSON-safe form.

get_type_safe_attr

Retrieve a single attribute, safely coerced for serialization.

validate_and_coerce

Pre-process raw field data to coerce UUIDs, Enums, dicts, and str fields.

get_all_type_safe_attr

Python
get_all_type_safe_attr(exclude_fields: Optional[List[str]] = None) -> Dict[str, Any]

Return all attributes in JSON-safe form.

Source code in xpytools/xtool/xpyt_pydantic/TypeSafeAccessMixin.py
Python
def get_all_type_safe_attr(self, exclude_fields: Optional[List[str]] = None) -> Dict[str, Any]:
    """Return all attributes in JSON-safe form."""
    exclude_fields = exclude_fields or []
    return {
            attr: self.get_type_safe_attr(attr)
            for attr in self.__dict__
            if attr not in exclude_fields
            }

get_type_safe_attr

Python
get_type_safe_attr(item: str) -> Any

Retrieve a single attribute, safely coerced for serialization.

Source code in xpytools/xtool/xpyt_pydantic/TypeSafeAccessMixin.py
Python
def get_type_safe_attr(self, item: str) -> Any:
    """Retrieve a single attribute, safely coerced for serialization."""
    if not hasattr(self, item):
        raise KeyError(f"'{item}' is not a valid field.")

    value = getattr(self, item)
    return self._coerce_single_value(value, field_name=item)

validate_and_coerce classmethod

Python
validate_and_coerce(values: Dict[str, Any]) -> Dict[str, Any]

Pre-process raw field data to coerce UUIDs, Enums, dicts, and str fields.

  • Converts UUID strings to UUID objects (if field type is UUID)
  • Converts Enums from names/values
  • Converts JSON-like strings to dicts
  • Normalizes None-like values
Source code in xpytools/xtool/xpyt_pydantic/TypeSafeAccessMixin.py
Python
@model_validator(mode="before")
@classmethod
def validate_and_coerce(cls, values: Dict[str, Any]) -> Dict[str, Any]:
    """
    Pre-process raw field data to coerce UUIDs, Enums, dicts, and str fields.

    - Converts UUID strings to UUID objects (if field type is UUID)
    - Converts Enums from names/values
    - Converts JSON-like strings to dicts
    - Normalizes None-like values
    """
    from ...xtype.xcast import as_json
    from ...xtype.xcheck import is_uuid, is_json_like

    coerced = {}
    for key, val in values.items():
        try:
            if is_none(val):
                coerced[key] = None
                continue

            # UUIDs
            if getattr(cls, "__annotations__", {}).get(key) == UUID and not is_uuid(val):
                from uuid import UUID as _UUID
                coerced[key] = _UUID(str(val))
                continue

            # JSON fields
            if is_json_like(val):
                coerced[key] = as_json(val)
                continue

            coerced[key] = val
        except Exception:
            coerced[key] = val  # fallback silently

    return coerced