from typing import Type
from typing import Union


def get_spec_class_for_type(
    attr_type: Type, allow_polymorphic=False
) -> Union[Type, None]:
    """
    Get the spec class to associated with a given attribute type. This is
    useful when `attr_type` is a polymorphic type, e.g.
    Union[SpecClass, str]. It works by finding the spec class type in the
    polymorphic type. If there is not exactly one spec class type, `None` is
    returned.
    """
    if hasattr(attr_type, "__spec_class__"):
        return attr_type
    if allow_polymorphic and getattr(attr_type, "__origin__", None) is Union:
        spec_classes = []
        for typ in attr_type.__args__:
            spec_typ = get_spec_class_for_type(typ)
            if spec_typ is not None:
                spec_classes.append(spec_typ)
        if len(spec_classes) == 1:
            return spec_classes[0]
    return None