Ensure that the given `hs` is an instance of :class:`LocalSpace`.

    If `hs` an instance of :class:`str` or :class:`int`, it will be converted
    to a `cls` (if possible). If it already is an instace of `cls`, `hs`
    will be returned unchanged.

    Args:
        hs (HilbertSpace or str or int): The Hilbert space (or label) to
            convert/check
        cls (type): The class to which an int/str label for a Hilbert space
            should be converted. Must be a subclass of :class:`LocalSpace`.

    Raises:
        TypeError: If `hs` is not a :class:`.LocalSpace`, :class:`str`, or
            :class:`int`.

    Returns:
        LocalSpace: original or converted `hs`

    Examples:
        >>> srepr(ensure_local_space(0))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space('tls'))
        "LocalSpace('tls')"
        >>> srepr(ensure_local_space(0, cls=LocalSpace))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0)))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0)))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0) * LocalSpace(1)))
        Traceback (most recent call last):
           ...
        TypeError: hs must be an instance of LocalSpace

def ensure_local_space(hs, cls=LocalSpace):
    """Ensure that the given `hs` is an instance of :class:`LocalSpace`.

    If `hs` an instance of :class:`str` or :class:`int`, it will be converted
    to a `cls` (if possible). If it already is an instace of `cls`, `hs`
    will be returned unchanged.

    Args:
        hs (HilbertSpace or str or int): The Hilbert space (or label) to
            convert/check
        cls (type): The class to which an int/str label for a Hilbert space
            should be converted. Must be a subclass of :class:`LocalSpace`.

    Raises:
        TypeError: If `hs` is not a :class:`.LocalSpace`, :class:`str`, or
            :class:`int`.

    Returns:
        LocalSpace: original or converted `hs`

    Examples:
        >>> srepr(ensure_local_space(0))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space('tls'))
        "LocalSpace('tls')"
        >>> srepr(ensure_local_space(0, cls=LocalSpace))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0)))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0)))
        "LocalSpace('0')"
        >>> srepr(ensure_local_space(LocalSpace(0) * LocalSpace(1)))
        Traceback (most recent call last):
           ...
        TypeError: hs must be an instance of LocalSpace
    """
    if isinstance(hs, (str, int)):
        try:
            hs = cls(hs)
        except TypeError as exc_info:
            raise TypeError(
                "Cannot convert %s '%s' into a %s instance: %s"
                % (hs.__class__.__name__, hs, cls.__name__, str(exc_info)))
    if not isinstance(hs, LocalSpace):
        raise TypeError("hs must be an instance of LocalSpace")
    return hs