def set_dims(self, dim, shape=None):
        """Return a new variable with given set of dimensions.
        This method might be used to attach new dimension(s) to variable.

        When possible, this operation does not copy this variable's data.

        Parameters
        ----------
        dim : str or sequence of str or dict
            Dimensions to include on the new variable. If a dict, values are
            used to provide the sizes of new dimensions; otherwise, new
            dimensions are inserted with length 1.

        Returns
        -------
        Variable
        """
        if isinstance(dim, str):
            dim = [dim]

        if shape is None and is_dict_like(dim):
            shape = tuple(dim.values())

        missing_dims = set(self.dims) - set(dim)
        if missing_dims:
            raise ValueError(
                f"new dimensions {dim!r} must be a superset of "
                f"existing dimensions {self.dims!r}"
            )

        self_dims = set(self.dims)
        expanded_dims = tuple(d for d in dim if d not in self_dims) + self.dims

        if self.dims == expanded_dims:
            # don't use broadcast_to unless necessary so the result remains
            # writeable if possible
            expanded_data = self.data
        elif shape is None or all(
            s == 1 for s, e in zip(shape, dim, strict=True) if e not in self_dims
        ):
            # "Trivial" broadcasting, i.e. simply inserting a new dimension
            # This is typically easier for duck arrays to implement
            # than the full "broadcast_to" semantics
            indexer = (None,) * (len(expanded_dims) - self.ndim) + (...,)
            expanded_data = self.data[indexer]
        else:  # elif shape is not None:
            dims_map = dict(zip(dim, shape, strict=True))
            tmp_shape = tuple(dims_map[d] for d in expanded_dims)
            expanded_data = duck_array_ops.broadcast_to(self._data, tmp_shape)

        expanded_var = Variable(
            expanded_dims, expanded_data, self._attrs, self._encoding, fastpath=True
        )
        return expanded_var.transpose(*dim)
Return a new variable with given set of dimensions.
        This method might be used to attach new dimension(s) to variable.

        When possible, this operation does not copy this variable's data.

        Parameters
        ----------
        dim : str or sequence of str or dict
            Dimensions to include on the new variable. If a dict, values are
            used to provide the sizes of new dimensions; otherwise, new
            dimensions are inserted with length 1.

        Returns
        -------
        Variable
        
xarray/core/variable.py