def _sort_for_union_preference()

in chz/tiepin.py [0:0]


def _sort_for_union_preference(typs: tuple[TypeForm, ...]):
    def sort_key(typ):
        typ = getattr(typ, "__origin__", typ)
        if typ is str:
            # sort str to last, because anything can be cast to str
            return 1
        if typ is typing.Literal or typ is typing_extensions.Literal:
            # sort literals to first, because they exact match
            return -2
        if typ is type(None) or typ is None:
            # None exact matches as well (like all singletons)
            return -1
        return 0

    # note this is a stable sort, so we preserve user ordering
    return sorted(typs, key=sort_key)