@@ -481,6 +481,15 @@ def _parse_dimensions(self, dims: _DimsLike) -> _Dims:
481481 f"dimensions { dims } must have the same length as the "
482482 f"number of data dimensions, ndim={ self .ndim } "
483483 )
484+ if len (set (dims )) < len (dims ):
485+ repeated_dims = set ([d for d in dims if dims .count (d ) > 1 ])
486+ warnings .warn (
487+ f"Duplicate dimension names present: dimensions { repeated_dims } appear more than once in dims={ dims } . "
488+ "We do not yet support duplicate dimension names, but we do allow initial construction of the object. "
489+ "We recommend you rename the dims immediately to become distinct, as most xarray functionality is likely to fail silently if you do not. "
490+ "To rename the dimensions you will need to set the ``.dims`` attribute of each variable, ``e.g. var.dims=('x0', 'x1')``." ,
491+ UserWarning ,
492+ )
484493 return dims
485494
486495 @property
@@ -651,6 +660,7 @@ def get_axis_num(self, dim: Hashable | Iterable[Hashable]) -> int | tuple[int, .
651660 return self ._get_axis_num (dim )
652661
653662 def _get_axis_num (self : Any , dim : Hashable ) -> int :
663+ _raise_if_any_duplicate_dimensions (self .dims )
654664 try :
655665 return self .dims .index (dim ) # type: ignore[no-any-return]
656666 except ValueError :
@@ -846,3 +856,13 @@ def _to_dense(self) -> NamedArray[Any, _DType_co]:
846856
847857
848858_NamedArray = NamedArray [Any , np .dtype [_ScalarType_co ]]
859+
860+
861+ def _raise_if_any_duplicate_dimensions (
862+ dims : _Dims , err_context : str = "This function"
863+ ) -> None :
864+ if len (set (dims )) < len (dims ):
865+ repeated_dims = set ([d for d in dims if dims .count (d ) > 1 ])
866+ raise ValueError (
867+ f"{ err_context } cannot handle duplicate dimensions, but dimensions { repeated_dims } appear more than once on this object's dims: { dims } "
868+ )
0 commit comments