import torch


def _padded_concatenate(tensors, dim, pad_width, pad_value):
    """
    Concatenate tensors along specified dimension, adding padding between them.

    Parameters
    ----------
    tensors : list of torch.Tensor
        Tensors to be concatenated.
    dim : int
        Dimension along witch to concatenate.
    pad_width : int
        Width of the padding along concatenation dimension.
    pad_value : numeric or list like
        Value to fill the padding tensor with. Can be list, e.g. RGBA for tensors with color as last dimension.

    Returns
    -------
    torch.Tensor

    """
    tensors = list(tensors)
    device = tensors[0].device
    if pad_width != 0:
        pad_shape = list(tensors[0].shape)
        pad_shape[dim] = pad_width
        if isinstance(pad_value, list):
            pad_value = torch.Tensor(pad_value).to(device).type_as(tensors[0])
        pad_tensor = torch.ones(pad_shape).to(device) * pad_value
        [tensors.insert(i, pad_tensor) for i in range(len(tensors)-1, 0, -1)]
    return torch.cat(tensors, dim=dim)