Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parse_dims func #7051

Merged
merged 16 commits into from
Nov 30, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
Hashable,
Iterable,
Iterator,
Literal,
Mapping,
MutableMapping,
MutableSet,
Expand Down Expand Up @@ -919,6 +920,72 @@ def drop_missing_dims(
)


@overload
def parse_dims(
dim: str | Iterable[Hashable] | None,
all_dims: tuple[Hashable, ...],
*,
check: bool = True,
replace_none: Literal[True] = True,
) -> tuple[Hashable, ...]:
...


@overload
def parse_dims(
dim: str | Iterable[Hashable] | None,
all_dims: tuple[Hashable, ...],
*,
check: bool = True,
replace_none: Literal[False],
) -> tuple[Hashable, ...] | None:
...


def parse_dims(
headtr1ck marked this conversation as resolved.
Show resolved Hide resolved
dim: str | Iterable[Hashable] | None,
all_dims: tuple[Hashable, ...],
*,
check: bool = True,
replace_none: bool = True,
) -> tuple[Hashable, ...] | None:
"""Parse one or more dimensions.

A single dimension must be always a str, multiple dimensions
can be Hashables. This supports e.g. using a tuple as a dimension.

Parameters
----------
dim : str, Iterable of Hashable or None
Dimension(s) to parse.
all_dims : tuple of Hashable
All possible dimensions.
check: bool, default: True
if True, check if dim is a subset of all_dims.
replace_none : bool, default: True
If True, return all_dims if dim is None.

Returns
-------
parsed_dims : tuple of Hashable
Input dimensions as a tuple.
"""
if dim is None:
if replace_none:
return all_dims
return None
if isinstance(dim, str):
dim = (dim,)
if check:
headtr1ck marked this conversation as resolved.
Show resolved Hide resolved
wrong_dims = set(dim) - set(all_dims)
if wrong_dims:
wrong_dims_str = ", ".join(f"'{d!s}'" for d in wrong_dims)
raise ValueError(
f"Dimension(s) {wrong_dims_str} do not exist. Expected one or more of {all_dims}"
)
return tuple(dim)


_Accessor = TypeVar("_Accessor")


Expand Down
43 changes: 42 additions & 1 deletion xarray/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from datetime import datetime
from typing import Hashable
from typing import Hashable, Iterable

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -294,6 +294,47 @@ def test_infix_dims_errors(supplied, all_):
list(utils.infix_dims(supplied, all_))


@pytest.mark.parametrize(
["dim", "expected"],
[
pytest.param("a", ("a",), id="str"),
pytest.param(["a", "b"], ("a", "b"), id="list_of_str"),
pytest.param(["a", 1], ("a", 1), id="list_mixed"),
pytest.param(("a", "b"), ("a", "b"), id="tuple_of_str"),
pytest.param(["a", ("b", "c")], ("a", ("b", "c")), id="list_with_tuple"),
pytest.param((("b", "c"),), (("b", "c"),), id="tuple_of_tuple"),
pytest.param(None, None, id="None"),
],
)
def test_parse_dims(
dim: str | Iterable[Hashable] | None,
expected: tuple[Hashable, ...],
) -> None:
all_dims = ("a", "b", 1, ("b", "c")) # selection of different Hashables
actual = utils.parse_dims(dim, all_dims, replace_none=False)
assert actual == expected


def test_parse_dims_replace_none() -> None:
all_dims = ("a", "b", 1, ("b", "c")) # selection of different Hashables
actual = utils.parse_dims(None, all_dims, replace_none=True)
assert actual == all_dims


@pytest.mark.parametrize(
"dim",
[
pytest.param("x", id="str_missing"),
pytest.param(["a", "x"], id="list_missing_one"),
pytest.param(["x", 2], id="list_missing_all"),
],
)
def test_parse_dims_raises(dim: str | Iterable[Hashable]) -> None:
all_dims = ("a", "b", 1, ("b", "c")) # selection of different Hashables
with pytest.raises(ValueError, match="'x'"):
utils.parse_dims(dim, all_dims, check=True)


@pytest.mark.parametrize(
"nested_list, expected",
[
Expand Down