def stack(
        cls, variables: Mapping[Any, Variable], dim: Hashable
    ) -> PandasMultiIndex:
        """Create a new Pandas MultiIndex from the product of 1-d variables (levels) along a
        new dimension.

        Level variables must have a dimension distinct from each other.

        Keeps levels the same (doesn't refactorize them) so that it gives back the original
        labels after a stack/unstack roundtrip.

        """
        _check_dim_compat(variables, all_dims="different")

        level_indexes = [safe_cast_to_index(var) for var in variables.values()]
        for name, idx in zip(variables, level_indexes, strict=True):
            if isinstance(idx, pd.MultiIndex):
                raise ValueError(
                    f"cannot create a multi-index along stacked dimension {dim!r} "
                    f"from variable {name!r} that wraps a multi-index"
                )

        # from_product sorts by default, so we can't use that always
        # https://github.com/pydata/xarray/issues/980
        # https://github.com/pandas-dev/pandas/issues/14672
        if all(index.is_monotonic_increasing for index in level_indexes):
            index = pd.MultiIndex.from_product(
                level_indexes, sortorder=0, names=variables.keys()
            )
        else:
            split_labels, levels = zip(
                *[lev.factorize() for lev in level_indexes], strict=True
            )
            labels_mesh = np.meshgrid(*split_labels, indexing="ij")
            labels = [x.ravel().tolist() for x in labels_mesh]

            index = pd.MultiIndex(
                levels=levels, codes=labels, sortorder=0, names=variables.keys()
            )
        level_coords_dtype = {k: var.dtype for k, var in variables.items()}

        return cls(index, dim, level_coords_dtype=level_coords_dtype)
Create a new Pandas MultiIndex from the product of 1-d variables (levels) along a
        new dimension.

        Level variables must have a dimension distinct from each other.

        Keeps levels the same (doesn't refactorize them) so that it gives back the original
        labels after a stack/unstack roundtrip.

        
xarray/core/indexes.py