Skip to content

erdantic.plugins.attrs

get_fields_from_attrs_class

get_fields_from_attrs_class(
    model: AttrsClassType,
) -> List[FieldInfo]

Given an attrs class, return a list of FieldInfo instances for each field in the class.

Parameters:

Name Type Description Default
model AttrsClassType

The attrs class to get fields from.

required

Returns:

Type Description
List[FieldInfo]

List of FieldInfo instances for each field in the class

Source code in erdantic/plugins/attrs.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
def get_fields_from_attrs_class(model: AttrsClassType) -> List[FieldInfo]:
    """Given an attrs class, return a list of FieldInfo instances for each field in the class.

    Args:
        model (AttrsClassType): The attrs class to get fields from.

    Returns:
        List[FieldInfo]: List of FieldInfo instances for each field in the class
    """
    try:
        # Try to automatically resolve forward references
        attrs.resolve_types(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"attrs class {model_full_name}. "
            "You should use attrs.resolve_types with locals() where you define the class."
        )
        raise UnresolvableForwardRefError(
            msg, name=forward_ref, model_full_name=model_full_name
        ) from e
    return [
        FieldInfo.from_raw_type(
            model_full_name=FullyQualifiedName.from_object(model),
            name=attrib.name,
            raw_type=attrib.type,
        )
        for attrib in attrs.fields(model)
    ]

is_attrs_class

is_attrs_class(obj: Any) -> TypeGuard[AttrsClassType]

Predicate function to determine if an object is an attrs class (not an instance).

Parameters:

Name Type Description Default
obj Any

The object to check.

required

Returns:

Type Description
bool

True if the object is an attrs class, False otherwise.

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

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

    Returns:
        bool: True if the object is an attrs class, False otherwise.
    """
    return isinstance(obj, type) and attrs.has(obj)