Skip to content

erdantic.plugins.msgspec

get_fields_from_msgspec_struct

get_fields_from_msgspec_struct(
    model: MsgspecStruct,
) -> list[FieldInfo]

Given a msgspec struct, return a list of FieldInfo instances for each field in the struct.

Parameters:

Name Type Description Default
model PydanticModel

The struct to get fields from.

required

Returns:

Type Description
list[FieldInfo]

List of FieldInfo instances for each field in the struct

Source code in erdantic/plugins/msgspec.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def get_fields_from_msgspec_struct(model: MsgspecStruct) -> list[FieldInfo]:
    """Given a msgspec struct, return a list of FieldInfo instances for each field in the
    struct.

    Args:
        model (PydanticModel): The struct to get fields from.

    Returns:
        list[FieldInfo]: List of FieldInfo instances for each field in the struct
    """
    try:
        msgspec._utils.get_class_annotations(model)  # type: ignore [attr-defined]
        return [
            FieldInfo.from_raw_type(
                model_full_name=FullyQualifiedName.from_object(model),
                name=msgspec_field_info.name,
                raw_type=msgspec_field_info.type,
            )
            for msgspec_field_info in msgspec.structs.fields(model)
        ]
    except NameError as e:
        model_full_name = FullyQualifiedName.from_object(model)
        forward_ref = getattr(
            e,
            "name",
            re.search(r"(?<=')(?:[^'])*(?=')", str(e)).group(0),  # type: ignore [union-attr]
        )
        msg = (
            f"Failed to resolve forward reference '{forward_ref}' in the type annotations for "
            f"struct {model_full_name}. "
            "erdantic does not currently support manually resolving forward references for "
            "structs."
        )
        raise UnresolvableForwardRefError(
            msg, name=forward_ref, model_full_name=model_full_name
        ) from e

is_msgspec_struct

is_msgspec_struct(obj: Any) -> TypeGuard[MsgspecStruct]

Predicate function to determine if an object is a msgspect struct (class, not instance).

Parameters:

Name Type Description Default
obj Any

The object to check.

required

Returns:

Type Description
bool

True if the object is a Struct class, False otherwise.

Source code in erdantic/plugins/msgspec.py
19
20
21
22
23
24
25
26
27
28
def is_msgspec_struct(obj: Any) -> TypeGuard[MsgspecStruct]:
    """Predicate function to determine if an object is a msgspect struct (class, not instance).

    Args:
        obj (Any): The object to check.

    Returns:
        bool: True if the object is a Struct class, False otherwise.
    """
    return isinstance(obj, type) and issubclass(obj, msgspec.Struct)