Skip to content

Commit 2629b2e

Browse files
committed
repo-review 2
1 parent 8779ba8 commit 2629b2e

9 files changed

+123
-73
lines changed

cf_xarray/accessor.py

+44-42
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
import inspect
55
import itertools
66
import re
7-
import warnings
87
from collections import ChainMap, namedtuple
98
from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequence
109
from datetime import datetime
1110
from typing import (
1211
Any,
1312
Callable,
13+
Literal,
1414
TypeVar,
1515
Union,
1616
cast,
@@ -48,6 +48,7 @@
4848
_get_version,
4949
_is_datetime_like,
5050
always_iterable,
51+
emit_user_level_warning,
5152
invert_mappings,
5253
parse_cell_methods_attr,
5354
parse_cf_standard_name_table,
@@ -222,7 +223,7 @@ def _get_custom_criteria(
222223
try:
223224
from regex import match as regex_match
224225
except ImportError:
225-
from re import match as regex_match # type: ignore
226+
from re import match as regex_match # type: ignore[no-redef]
226227

227228
if isinstance(obj, DataArray):
228229
obj = obj._to_temp_dataset()
@@ -358,8 +359,6 @@ def _get_measure(obj: DataArray | Dataset, key: str) -> list[str]:
358359
if key in measures:
359360
results.update([measures[key]])
360361

361-
if isinstance(results, str):
362-
return [results]
363362
return list(results)
364363

365364

@@ -453,7 +452,7 @@ def _get_all(obj: DataArray | Dataset, key: Hashable) -> list[Hashable]:
453452
"""
454453
all_mappers: tuple[Mapper] = (
455454
_get_custom_criteria,
456-
functools.partial(_get_custom_criteria, criteria=cf_role_criteria), # type: ignore
455+
functools.partial(_get_custom_criteria, criteria=cf_role_criteria), # type: ignore[assignment]
457456
functools.partial(_get_custom_criteria, criteria=grid_mapping_var_criteria),
458457
_get_axis_coord,
459458
_get_measure,
@@ -491,7 +490,7 @@ def _get_coords(obj: DataArray | Dataset, key: Hashable) -> list[Hashable]:
491490
def _variables(func: F) -> F:
492491
@functools.wraps(func)
493492
def wrapper(obj: DataArray | Dataset, key: Hashable) -> list[DataArray]:
494-
return [obj[k] for k in func(obj, key)] # type: ignore[misc]
493+
return [obj[k] for k in func(obj, key)]
495494

496495
return cast(F, wrapper)
497496

@@ -636,10 +635,10 @@ def _getattr(
636635
):
637636
raise AttributeError(
638637
f"{obj.__class__.__name__+'.cf'!r} object has no attribute {attr!r}"
639-
)
638+
) from None
640639
raise AttributeError(
641640
f"{attr!r} is not a valid attribute on the underlying xarray object."
642-
)
641+
) from None
643642

644643
if isinstance(attribute, Mapping):
645644
if not attribute:
@@ -663,7 +662,7 @@ def _getattr(
663662
newmap.update(dict.fromkeys(inverted[key], value))
664663
newmap.update({key: attribute[key] for key in unused_keys})
665664

666-
skip: dict[str, list[Hashable] | None] = {
665+
skip: dict[str, list[Literal["coords", "measures"]] | None] = {
667666
"data_vars": ["coords"],
668667
"coords": None,
669668
}
@@ -672,7 +671,7 @@ def _getattr(
672671
newmap[key] = _getitem(accessor, key, skip=skip[attr])
673672
return newmap
674673

675-
elif isinstance(attribute, Callable): # type: ignore
674+
elif isinstance(attribute, Callable): # type: ignore[arg-type]
676675
func: Callable = attribute
677676

678677
else:
@@ -704,7 +703,7 @@ def wrapper(*args, **kwargs):
704703
def _getitem(
705704
accessor: CFAccessor,
706705
key: Hashable,
707-
skip: list[Hashable] | None = None,
706+
skip: list[Literal["coords", "measures"]] | None = None,
708707
) -> DataArray:
709708
...
710709

@@ -713,15 +712,15 @@ def _getitem(
713712
def _getitem(
714713
accessor: CFAccessor,
715714
key: Iterable[Hashable],
716-
skip: list[Hashable] | None = None,
715+
skip: list[Literal["coords", "measures"]] | None = None,
717716
) -> Dataset:
718717
...
719718

720719

721720
def _getitem(
722-
accessor,
723-
key,
724-
skip=None,
721+
accessor: CFAccessor,
722+
key: Hashable | Iterable[Hashable],
723+
skip: list[Literal["coords", "measures"]] | None = None,
725724
):
726725
"""
727726
Index into obj using key. Attaches CF associated variables.
@@ -772,7 +771,7 @@ def check_results(names, key):
772771
measures = accessor._get_all_cell_measures()
773772
except ValueError:
774773
measures = []
775-
warnings.warn("Ignoring bad cell_measures attribute.", UserWarning)
774+
emit_user_level_warning("Ignoring bad cell_measures attribute.", UserWarning)
776775

777776
if isinstance(obj, Dataset):
778777
grid_mapping_names = list(accessor.grid_mapping_names)
@@ -835,14 +834,15 @@ def check_results(names, key):
835834
)
836835
coords.extend(itertools.chain(*extravars.values()))
837836

837+
ds: Dataset
838838
if isinstance(obj, DataArray):
839839
ds = obj._to_temp_dataset()
840840
else:
841841
ds = obj
842842

843843
if scalar_key:
844844
if len(allnames) == 1:
845-
da: DataArray = ds.reset_coords()[allnames[0]] # type: ignore
845+
da: DataArray = ds.reset_coords()[allnames[0]]
846846
if allnames[0] in coords:
847847
coords.remove(allnames[0])
848848
for k1 in coords:
@@ -857,26 +857,27 @@ def check_results(names, key):
857857

858858
ds = ds.reset_coords()[varnames + coords]
859859
if isinstance(obj, DataArray):
860-
if scalar_key and len(ds.variables) == 1:
861-
# single dimension coordinates
862-
assert coords
863-
assert not varnames
860+
if scalar_key:
861+
if len(ds.variables) == 1:
862+
# single dimension coordinates
863+
assert coords
864+
assert not varnames
864865

865-
return ds[coords[0]]
866+
return ds[coords[0]]
866867

867-
elif scalar_key and len(ds.variables) > 1:
868-
raise NotImplementedError(
869-
"Not sure what to return when given scalar key for DataArray and it has multiple values. "
870-
"Please open an issue."
871-
)
868+
else:
869+
raise NotImplementedError(
870+
"Not sure what to return when given scalar key for DataArray and it has multiple values. "
871+
"Please open an issue."
872+
)
872873

873874
return ds.set_coords(coords)
874875

875876
except KeyError:
876877
raise KeyError(
877878
f"{kind}.cf does not understand the key {k!r}. "
878879
f"Use 'repr({kind}.cf)' (or '{kind}.cf' in a Jupyter environment) to see a list of key names that can be interpreted."
879-
)
880+
) from None
880881

881882

882883
def _possible_x_y_plot(obj, key, skip=None):
@@ -1115,7 +1116,7 @@ def _assert_valid_other_comparison(self, other):
11151116
)
11161117
return flag_dict
11171118

1118-
def __eq__(self, other) -> DataArray: # type: ignore
1119+
def __eq__(self, other) -> DataArray:
11191120
"""
11201121
Compare flag values against `other`.
11211122
@@ -1125,7 +1126,7 @@ def __eq__(self, other) -> DataArray: # type: ignore
11251126
"""
11261127
return self._extract_flags([other])[other].rename(self._obj.name)
11271128

1128-
def __ne__(self, other) -> DataArray: # type: ignore
1129+
def __ne__(self, other) -> DataArray:
11291130
"""
11301131
Compare flag values against `other`.
11311132
@@ -1247,7 +1248,7 @@ def curvefit(
12471248
coords_iter = coords
12481249
coords = [
12491250
apply_mapper(
1250-
[_single(_get_coords)], self._obj, v, error=False, default=[v] # type: ignore
1251+
[_single(_get_coords)], self._obj, v, error=False, default=[v] # type: ignore[arg-type]
12511252
)[0]
12521253
for v in coords_iter
12531254
]
@@ -1258,7 +1259,7 @@ def curvefit(
12581259
reduce_dims_iter = list(reduce_dims)
12591260
reduce_dims = [
12601261
apply_mapper(
1261-
[_single(_get_dims)], self._obj, v, error=False, default=[v] # type: ignore
1262+
[_single(_get_dims)], self._obj, v, error=False, default=[v] # type: ignore[arg-type]
12621263
)[0]
12631264
for v in reduce_dims_iter
12641265
]
@@ -1353,7 +1354,7 @@ def _rewrite_values(
13531354

13541355
# allow multiple return values here.
13551356
# these are valid for .sel, .isel, .coarsen
1356-
all_mappers = ChainMap( # type: ignore
1357+
all_mappers = ChainMap( # type: ignore[misc]
13571358
key_mappers,
13581359
dict.fromkeys(var_kws, (_get_all,)),
13591360
)
@@ -1442,7 +1443,7 @@ def describe(self):
14421443
Print a string repr to screen.
14431444
"""
14441445

1445-
warnings.warn(
1446+
emit_user_level_warning(
14461447
"'obj.cf.describe()' will be removed in a future version. "
14471448
"Use instead 'repr(obj.cf)' or 'obj.cf' in a Jupyter environment.",
14481449
DeprecationWarning,
@@ -1610,10 +1611,9 @@ def cell_measures(self) -> dict[str, list[Hashable]]:
16101611
bad_vars = list(
16111612
as_dataset.filter_by_attrs(cell_measures=attr).data_vars.keys()
16121613
)
1613-
warnings.warn(
1614+
emit_user_level_warning(
16141615
f"Ignoring bad cell_measures attribute: {attr} on {bad_vars}.",
16151616
UserWarning,
1616-
stacklevel=2,
16171617
)
16181618
measures = {
16191619
key: self._drop_missing_variables(_get_all(self._obj, key)) for key in keys
@@ -1730,9 +1730,9 @@ def get_associated_variable_names(
17301730
except ValueError as e:
17311731
if error:
17321732
msg = e.args[0] + " Ignore this error by passing 'error=False'"
1733-
raise ValueError(msg)
1733+
raise ValueError(msg) from None
17341734
else:
1735-
warnings.warn(
1735+
emit_user_level_warning(
17361736
f"Ignoring bad cell_measures attribute: {attrs_or_encoding['cell_measures']}",
17371737
UserWarning,
17381738
)
@@ -1764,7 +1764,7 @@ def get_associated_variable_names(
17641764
missing = set(allvars) - set(self._maybe_to_dataset()._variables)
17651765
if missing:
17661766
if OPTIONS["warn_on_missing_variables"]:
1767-
warnings.warn(
1767+
emit_user_level_warning(
17681768
f"Variables {missing!r} not found in object but are referred to in the CF attributes.",
17691769
UserWarning,
17701770
)
@@ -1877,7 +1877,7 @@ def get_renamer_and_conflicts(keydict):
18771877

18781878
# Rename and warn
18791879
if conflicts:
1880-
warnings.warn(
1880+
emit_user_level_warning(
18811881
"Conflicting variables skipped:\n"
18821882
+ "\n".join(
18831883
[
@@ -2585,10 +2585,12 @@ def decode_vertical_coords(self, *, outnames=None, prefix=None):
25852585
try:
25862586
zname = outnames[dim]
25872587
except KeyError:
2588-
raise KeyError("Your `outnames` need to include a key of `dim`.")
2588+
raise KeyError(
2589+
"Your `outnames` need to include a key of `dim`."
2590+
) from None
25892591

25902592
else:
2591-
warnings.warn(
2593+
emit_user_level_warning(
25922594
"`prefix` is being deprecated; use `outnames` instead.",
25932595
DeprecationWarning,
25942596
)

cf_xarray/criteria.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@
128128
coordinate_criteria["time"] = coordinate_criteria["T"]
129129

130130
# "long_name" and "standard_name" criteria are the same. For convenience.
131-
for coord, attrs in coordinate_criteria.items():
131+
for coord in coordinate_criteria:
132132
coordinate_criteria[coord]["long_name"] = coordinate_criteria[coord][
133133
"standard_name"
134134
]

cf_xarray/formatting.py

+7-15
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
try:
1111
from rich.table import Table
1212
except ImportError:
13-
Table = None # type: ignore
13+
Table = None # type: ignore[assignment, misc]
1414

1515

1616
def _format_missing_row(row: str, rich: bool) -> str:
@@ -41,7 +41,7 @@ def _format_cf_name(name: str, rich: bool) -> str:
4141
def make_text_section(
4242
accessor,
4343
subtitle: str,
44-
attr: str,
44+
attr: str | dict,
4545
dims=None,
4646
valid_keys=None,
4747
valid_values=None,
@@ -140,10 +140,10 @@ def _maybe_panel(textgen, title: str, rich: bool):
140140
width=100,
141141
)
142142
if isinstance(textgen, Table):
143-
return Panel(textgen, padding=(0, 20), **kwargs) # type: ignore
143+
return Panel(textgen, padding=(0, 20), **kwargs) # type: ignore[arg-type]
144144
else:
145145
text = "".join(textgen)
146-
return Panel(f"[color(241)]{text.rstrip()}[/color(241)]", **kwargs) # type: ignore
146+
return Panel(f"[color(241)]{text.rstrip()}[/color(241)]", **kwargs) # type: ignore[arg-type]
147147
else:
148148
text = "".join(textgen)
149149
return title + ":\n" + text
@@ -220,22 +220,14 @@ def _format_flags(accessor, rich):
220220
table.add_column("Value", justify="right")
221221
table.add_column("Bits", justify="center")
222222

223-
for val, bit, (key, (mask, value)) in zip(
224-
value_text, bit_text, flag_dict.items()
225-
):
226-
table.add_row(
227-
_format_cf_name(key, rich),
228-
val,
229-
bit,
230-
)
223+
for val, bit, key in zip(value_text, bit_text, flag_dict):
224+
table.add_row(_format_cf_name(key, rich), val, bit)
231225

232226
return table
233227

234228
else:
235229
rows = []
236-
for val, bit, (key, (mask, value)) in zip(
237-
value_text, bit_text, flag_dict.items()
238-
):
230+
for val, bit, key in zip(value_text, bit_text, flag_dict):
239231
rows.append(f"{TAB}{_format_cf_name(key, rich)}: {TAB} {val} {bit}")
240232
return _print_rows("Flag Meanings", rows, rich)
241233

cf_xarray/options.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class set_options:
4747

4848
def __init__(self, **kwargs):
4949
self.old = {}
50-
for k, v in kwargs.items():
50+
for k in kwargs:
5151
if k not in OPTIONS:
5252
raise ValueError(
5353
f"argument name {k!r} is not in the set of valid options {set(OPTIONS)!r}"
@@ -57,7 +57,7 @@ def __init__(self, **kwargs):
5757

5858
def _apply_update(self, options_dict):
5959
options_dict = copy.deepcopy(options_dict)
60-
for k, v in options_dict.items():
60+
for k in options_dict:
6161
if k == "custom_criteria":
6262
options_dict["custom_criteria"] = always_iterable(
6363
options_dict["custom_criteria"], allowed=(tuple, list)

0 commit comments

Comments
 (0)