Skip to content

pydantic_compat

pydantic_compat

Low-level Pydantic annotation compatibility helpers.

Functions:

Name Description
unwrap_optional_annotation

Unwrap Annotated and a union with one non-None member.

nested_model_type

Return the nested model type when an annotation has one compatible model.

unwrap_optional_annotation(annotation)

Unwrap Annotated and a union with one non-None member.

Source code in src/nemo_safe_synthesizer/configurator/pydantic_compat.py
def unwrap_optional_annotation(annotation: object) -> object:
    """Unwrap ``Annotated`` and a union with one non-``None`` member."""
    while get_origin(annotation) is Annotated:
        annotation = get_args(annotation)[0]
    origin = get_origin(annotation)
    if origin not in (types.UnionType, Union):
        return annotation
    members = tuple(unwrap_optional_annotation(item) for item in get_args(annotation) if item is not type(None))
    return members[0] if len(members) == 1 else annotation

nested_model_type(annotation, expected_base)

Return the nested model type when an annotation has one compatible model.

Source code in src/nemo_safe_synthesizer/configurator/pydantic_compat.py
def nested_model_type(annotation: object, expected_base: type[ModelT]) -> type[ModelT] | None:
    """Return the nested model type when an annotation has one compatible model."""
    annotation = unwrap_optional_annotation(annotation)
    if isinstance(annotation, type) and issubclass(annotation, expected_base):
        return annotation
    return None