def _field_to_type()

in src/cloudformation_cli_python_lib/recast.py [0:0]


def _field_to_type(field: Any, key: str, classes: Dict[str, Any]) -> Any:  # noqa: C901
    if field in [int, float, str, bool, typing.Any]:
        return field
    # If it's a ForwardRef we need to find base type
    if isinstance(field, get_forward_ref_type()):
        # Assuming codegen added an _ as a prefix, removing it and then getting the
        # class from model classes
        return classes[field.__forward_arg__[1:]]
    # Assuming this is a generic object created by typing.Union
    try:
        possible_types = field.__args__
        if not possible_types:
            raise InvalidRequest(f"Cannot process type {field} for field {key}")
    except AttributeError as attribute_error:
        raise InvalidRequest(
            f"Cannot process type {field} for field {key}"
        ) from attribute_error
    # Assuming that the union is generated from typing.Optional, so only
    # contains one type and None
    # pylint: disable=unidiomatic-typecheck
    fields = [t for t in possible_types if type(None) != t]
    if len(fields) != 1:
        raise InvalidRequest(f"Cannot process type {field} for field {key}")
    field = fields[0]
    # If it's a primitive we're done
    if field in [int, float, str, bool, typing.Any]:
        return field
    # If it's a ForwardRef we need to find base type
    if isinstance(field, get_forward_ref_type()):
        # Assuming codegen added an _ as a prefix, removing it and then getting the
        # class from model classes
        return classes[field.__forward_arg__[1:]]
    # reduce Sequence/AbstractSet to inner type
    if str(field).startswith("typing.Sequence") or str(field).startswith(
        "typing.AbstractSet"
    ):
        return _field_to_type(field.__args__[0], key, classes)
    if str(field).startswith("typing.MutableMapping"):
        return _field_to_type(field.__args__[1], key, classes)
    # If it's a type we don't know how to handle, we bail
    raise InvalidRequest(f"Cannot process type {field} for field {key}")