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

Don't apply mappers to DataArrays #227

Merged
merged 5 commits into from
May 27, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 15 additions & 6 deletions cf_xarray/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@

from .criteria import coordinate_criteria, regex
from .helpers import bounds_to_vertices
from .utils import _is_datetime_like, invert_mappings, parse_cell_methods_attr
from .utils import (
_is_datetime_like,
always_iterable,
invert_mappings,
parse_cell_methods_attr,
)

#: Classes wrapped by cf_xarray.
_WRAPPED_CLASSES = (
Expand Down Expand Up @@ -68,7 +73,7 @@
def apply_mapper(
mappers: Union[Mapper, Tuple[Mapper, ...]],
obj: Union[DataArray, Dataset],
key: str,
key: Any,
error: bool = True,
default: Any = None,
) -> List[Any]:
Expand All @@ -79,8 +84,13 @@ def apply_mapper(
It should return a list in all other cases including when there are no
results for a good key.
"""
if default is None:
default = []

if not isinstance(key, str):
if default is None:
raise ValueError("`default` must be provided when `key` is not a string.")
return list(always_iterable(default))

default = [] if default is None else list(always_iterable(default))

def _apply_single_mapper(mapper):

Expand Down Expand Up @@ -917,8 +927,7 @@ def _rewrite_values(
value = kwargs[key]
mappers = all_mappers[key]

if isinstance(value, str):
value = [value]
value = always_iterable(value)

if isinstance(value, dict):
# this for things like isel where **kwargs captures things like T=5
Expand Down
9 changes: 7 additions & 2 deletions cf_xarray/tests/test_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,13 @@ def test_weighted(obj):
with raise_if_dask_computes(max_computes=2):
# weights are checked for nans
expected = obj.weighted(obj["cell_area"]).sum("lat")
actual = obj.cf.weighted("area").sum("Y")
assert_identical(expected, actual)
actuals = [
obj.cf.weighted("area").sum("Y"),
obj.cf.weighted(obj["cell_area"]).sum("Y"),
obj.cf.weighted(weights=obj["cell_area"]).sum("Y"),
]
for actual in actuals:
assert_identical(expected, actual)


@pytest.mark.parametrize("obj", objects)
Expand Down
6 changes: 5 additions & 1 deletion cf_xarray/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections import defaultdict
from typing import Dict
from typing import Any, Dict, Iterable

from xarray import DataArray

Expand Down Expand Up @@ -53,3 +53,7 @@ def invert_mappings(*mappings):
for name in v:
merged[name] |= {k}
return merged


def always_iterable(obj: Any) -> Iterable:
return [obj] if not isinstance(obj, (tuple, list, set, dict)) else obj
19 changes: 18 additions & 1 deletion doc/examples/introduction.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@
"import xarray as xr"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`cf_xarray` works best when `xarray` keeps attributes by default.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"xr.set_options(keep_attrs=True)"
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we've been running the intro notebook without xr.set_options(keep_attrs=True).
I don't think the issue without it was triggered by this PR, but I might be wrong.

Anyways, I think we should keep attributes and maybe re-discuss #77?

]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -914,6 +930,7 @@
" * 110e3\n",
")\n",
"# and set proper attributes\n",
"ds[\"cell_area\"].attrs = dict(standard_name=\"cell_area\", units=\"m2\")\n",
"ds.air.attrs[\"cell_measures\"] = \"area: cell_area\""
]
},
Expand Down Expand Up @@ -1000,7 +1017,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.8.10"
},
"toc": {
"base_numbering": 1,
Expand Down