import types


def get_xref_type(obj):
    """
    Infer the Sphinx type a cross reference to ``obj`` should have.

    For example, ``:py:class`FooBar`` has the type ``py:class``.
    """
    if isinstance(obj, type):
        if issubclass(obj, BaseException):
            t = 'exc'
        else:
            t = 'class'
    elif isinstance(obj, types.ModuleType):
        t = 'mod'
    elif callable(obj):
        try:
            qualname = obj.__qualname__
        except AttributeError:
            t = 'func'
        else:
            if len(qualname.split('.')) > 1:
                t = 'meth'
            else:
                t = 'func'
    else:
        raise ValueError(f'Cannot infer the xref type of {obj}')

    return f'py:{t}'