import torch


def _set_tensor(var, name, length, dtype, dtype_torch):
    """Set and check a Tensor.

    Args:
        var: list, tuple, Tensor, or scalar of type dtype
        name: String specifying the name to use in error messages
        length: List specifying the desired length
        dtype: The Python type that var must have
        dtype_torch: The PyTorch type that the Tensor must have
    """
    # Convert to list if a scalar
    if isinstance(var, dtype):
        var = [var] * length

    # Check is a list, tuple, or Tensor
    if not isinstance(var, (list, tuple, torch.Tensor)):
        raise TypeError(
            "Expected {} to be a list, tuple, Tensor, or {}, "
            "but got {}".format(name, dtype, type(var))
        )

    # Check has correct length
    if len(var) != length:
        raise RuntimeError(
            "{} must have length {}, but got {}".format(name, length, len(var))
        )

    # Convert to Tensor
    if not isinstance(var, torch.Tensor):
        var = torch.tensor(var)

    # Convert to desired dtype
    var = var.to(dtype_torch)

    return var