Skip to content

Attrs integration

provide.foundation.parsers.attrs_integration

TODO: Add module docstring.

Functions

auto_parse

auto_parse(attr: Any, value: str) -> Any

Automatically parse value based on an attrs field's type and metadata.

This function first checks for a converter in the field's metadata, then falls back to type-based parsing.

Parameters:

Name Type Description Default
attr Any

attrs field (from fields(Class))

required
value str

String value to parse

required

Returns:

Type Description
Any

Parsed value based on field type or converter

Examples:

>>> from attrs import define, field, fields
>>> @define
... class Config:
...     count: int = field()
...     enabled: bool = field()
...     custom: str = field(converter=lambda x: x.upper())
>>> c = Config(count=0, enabled=False, custom="")
>>> auto_parse(fields(Config).count, "42")
42
>>> auto_parse(fields(Config).enabled, "true")
True
>>> auto_parse(fields(Config).custom, "hello")
'HELLO'
Source code in provide/foundation/parsers/attrs_integration.py
def auto_parse(attr: Any, value: str) -> Any:
    """Automatically parse value based on an attrs field's type and metadata.

    This function first checks for a converter in the field's metadata,
    then falls back to type-based parsing.

    Args:
        attr: attrs field (from fields(Class))
        value: String value to parse

    Returns:
        Parsed value based on field type or converter

    Examples:
        >>> from attrs import define, field, fields
        >>> @define
        ... class Config:
        ...     count: int = field()
        ...     enabled: bool = field()
        ...     custom: str = field(converter=lambda x: x.upper())
        >>> c = Config(count=0, enabled=False, custom="")
        >>> auto_parse(fields(Config).count, "42")
        42
        >>> auto_parse(fields(Config).enabled, "true")
        True
        >>> auto_parse(fields(Config).custom, "hello")
        'HELLO'

    """
    # Check for attrs field converter first
    if hasattr(attr, "converter"):
        success, result = _try_converter(attr.converter, value)
        if success:
            return result

    # Check for converter in metadata as fallback
    if hasattr(attr, "metadata") and attr.metadata:
        converter = attr.metadata.get("converter")
        success, result = _try_converter(converter, value)
        if success:
            return result

    # Get type hint from attrs field and try type-based parsing
    field_type = _extract_field_type(attr)
    if field_type is not None:
        return parse_typed_value(value, field_type)

    # No type info, return as string
    return value