4
4
import inspect
5
5
import itertools
6
6
import re
7
- import warnings
8
7
from collections import ChainMap , namedtuple
9
8
from collections .abc import Hashable , Iterable , Mapping , MutableMapping , Sequence
10
9
from datetime import datetime
11
10
from typing import (
12
11
Any ,
13
12
Callable ,
13
+ Literal ,
14
14
TypeVar ,
15
15
Union ,
16
16
cast ,
48
48
_get_version ,
49
49
_is_datetime_like ,
50
50
always_iterable ,
51
+ emit_user_level_warning ,
51
52
invert_mappings ,
52
53
parse_cell_methods_attr ,
53
54
parse_cf_standard_name_table ,
@@ -222,7 +223,7 @@ def _get_custom_criteria(
222
223
try :
223
224
from regex import match as regex_match
224
225
except ImportError :
225
- from re import match as regex_match # type: ignore
226
+ from re import match as regex_match # type: ignore[no-redef]
226
227
227
228
if isinstance (obj , DataArray ):
228
229
obj = obj ._to_temp_dataset ()
@@ -358,8 +359,6 @@ def _get_measure(obj: DataArray | Dataset, key: str) -> list[str]:
358
359
if key in measures :
359
360
results .update ([measures [key ]])
360
361
361
- if isinstance (results , str ):
362
- return [results ]
363
362
return list (results )
364
363
365
364
@@ -453,7 +452,7 @@ def _get_all(obj: DataArray | Dataset, key: Hashable) -> list[Hashable]:
453
452
"""
454
453
all_mappers : tuple [Mapper ] = (
455
454
_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]
457
456
functools .partial (_get_custom_criteria , criteria = grid_mapping_var_criteria ),
458
457
_get_axis_coord ,
459
458
_get_measure ,
@@ -491,7 +490,7 @@ def _get_coords(obj: DataArray | Dataset, key: Hashable) -> list[Hashable]:
491
490
def _variables (func : F ) -> F :
492
491
@functools .wraps (func )
493
492
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 )]
495
494
496
495
return cast (F , wrapper )
497
496
@@ -636,10 +635,10 @@ def _getattr(
636
635
):
637
636
raise AttributeError (
638
637
f"{ obj .__class__ .__name__ + '.cf' !r} object has no attribute { attr !r} "
639
- )
638
+ ) from None
640
639
raise AttributeError (
641
640
f"{ attr !r} is not a valid attribute on the underlying xarray object."
642
- )
641
+ ) from None
643
642
644
643
if isinstance (attribute , Mapping ):
645
644
if not attribute :
@@ -663,7 +662,7 @@ def _getattr(
663
662
newmap .update (dict .fromkeys (inverted [key ], value ))
664
663
newmap .update ({key : attribute [key ] for key in unused_keys })
665
664
666
- skip : dict [str , list [Hashable ] | None ] = {
665
+ skip : dict [str , list [Literal [ "coords" , "measures" ] ] | None ] = {
667
666
"data_vars" : ["coords" ],
668
667
"coords" : None ,
669
668
}
@@ -672,7 +671,7 @@ def _getattr(
672
671
newmap [key ] = _getitem (accessor , key , skip = skip [attr ])
673
672
return newmap
674
673
675
- elif isinstance (attribute , Callable ): # type: ignore
674
+ elif isinstance (attribute , Callable ): # type: ignore[arg-type]
676
675
func : Callable = attribute
677
676
678
677
else :
@@ -704,7 +703,7 @@ def wrapper(*args, **kwargs):
704
703
def _getitem (
705
704
accessor : CFAccessor ,
706
705
key : Hashable ,
707
- skip : list [Hashable ] | None = None ,
706
+ skip : list [Literal [ "coords" , "measures" ] ] | None = None ,
708
707
) -> DataArray :
709
708
...
710
709
@@ -713,15 +712,15 @@ def _getitem(
713
712
def _getitem (
714
713
accessor : CFAccessor ,
715
714
key : Iterable [Hashable ],
716
- skip : list [Hashable ] | None = None ,
715
+ skip : list [Literal [ "coords" , "measures" ] ] | None = None ,
717
716
) -> Dataset :
718
717
...
719
718
720
719
721
720
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 ,
725
724
):
726
725
"""
727
726
Index into obj using key. Attaches CF associated variables.
@@ -772,7 +771,7 @@ def check_results(names, key):
772
771
measures = accessor ._get_all_cell_measures ()
773
772
except ValueError :
774
773
measures = []
775
- warnings . warn ("Ignoring bad cell_measures attribute." , UserWarning )
774
+ emit_user_level_warning ("Ignoring bad cell_measures attribute." , UserWarning )
776
775
777
776
if isinstance (obj , Dataset ):
778
777
grid_mapping_names = list (accessor .grid_mapping_names )
@@ -835,14 +834,15 @@ def check_results(names, key):
835
834
)
836
835
coords .extend (itertools .chain (* extravars .values ()))
837
836
837
+ ds : Dataset
838
838
if isinstance (obj , DataArray ):
839
839
ds = obj ._to_temp_dataset ()
840
840
else :
841
841
ds = obj
842
842
843
843
if scalar_key :
844
844
if len (allnames ) == 1 :
845
- da : DataArray = ds .reset_coords ()[allnames [0 ]] # type: ignore
845
+ da : DataArray = ds .reset_coords ()[allnames [0 ]]
846
846
if allnames [0 ] in coords :
847
847
coords .remove (allnames [0 ])
848
848
for k1 in coords :
@@ -857,26 +857,27 @@ def check_results(names, key):
857
857
858
858
ds = ds .reset_coords ()[varnames + coords ]
859
859
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
864
865
865
- return ds [coords [0 ]]
866
+ return ds [coords [0 ]]
866
867
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
+ )
872
873
873
874
return ds .set_coords (coords )
874
875
875
876
except KeyError :
876
877
raise KeyError (
877
878
f"{ kind } .cf does not understand the key { k !r} . "
878
879
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
880
881
881
882
882
883
def _possible_x_y_plot (obj , key , skip = None ):
@@ -1115,7 +1116,7 @@ def _assert_valid_other_comparison(self, other):
1115
1116
)
1116
1117
return flag_dict
1117
1118
1118
- def __eq__ (self , other ) -> DataArray : # type: ignore
1119
+ def __eq__ (self , other ) -> DataArray :
1119
1120
"""
1120
1121
Compare flag values against `other`.
1121
1122
@@ -1125,7 +1126,7 @@ def __eq__(self, other) -> DataArray: # type: ignore
1125
1126
"""
1126
1127
return self ._extract_flags ([other ])[other ].rename (self ._obj .name )
1127
1128
1128
- def __ne__ (self , other ) -> DataArray : # type: ignore
1129
+ def __ne__ (self , other ) -> DataArray :
1129
1130
"""
1130
1131
Compare flag values against `other`.
1131
1132
@@ -1247,7 +1248,7 @@ def curvefit(
1247
1248
coords_iter = coords
1248
1249
coords = [
1249
1250
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]
1251
1252
)[0 ]
1252
1253
for v in coords_iter
1253
1254
]
@@ -1258,7 +1259,7 @@ def curvefit(
1258
1259
reduce_dims_iter = list (reduce_dims )
1259
1260
reduce_dims = [
1260
1261
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]
1262
1263
)[0 ]
1263
1264
for v in reduce_dims_iter
1264
1265
]
@@ -1353,7 +1354,7 @@ def _rewrite_values(
1353
1354
1354
1355
# allow multiple return values here.
1355
1356
# these are valid for .sel, .isel, .coarsen
1356
- all_mappers = ChainMap ( # type: ignore
1357
+ all_mappers = ChainMap ( # type: ignore[misc]
1357
1358
key_mappers ,
1358
1359
dict .fromkeys (var_kws , (_get_all ,)),
1359
1360
)
@@ -1442,7 +1443,7 @@ def describe(self):
1442
1443
Print a string repr to screen.
1443
1444
"""
1444
1445
1445
- warnings . warn (
1446
+ emit_user_level_warning (
1446
1447
"'obj.cf.describe()' will be removed in a future version. "
1447
1448
"Use instead 'repr(obj.cf)' or 'obj.cf' in a Jupyter environment." ,
1448
1449
DeprecationWarning ,
@@ -1610,10 +1611,9 @@ def cell_measures(self) -> dict[str, list[Hashable]]:
1610
1611
bad_vars = list (
1611
1612
as_dataset .filter_by_attrs (cell_measures = attr ).data_vars .keys ()
1612
1613
)
1613
- warnings . warn (
1614
+ emit_user_level_warning (
1614
1615
f"Ignoring bad cell_measures attribute: { attr } on { bad_vars } ." ,
1615
1616
UserWarning ,
1616
- stacklevel = 2 ,
1617
1617
)
1618
1618
measures = {
1619
1619
key : self ._drop_missing_variables (_get_all (self ._obj , key )) for key in keys
@@ -1730,9 +1730,9 @@ def get_associated_variable_names(
1730
1730
except ValueError as e :
1731
1731
if error :
1732
1732
msg = e .args [0 ] + " Ignore this error by passing 'error=False'"
1733
- raise ValueError (msg )
1733
+ raise ValueError (msg ) from None
1734
1734
else :
1735
- warnings . warn (
1735
+ emit_user_level_warning (
1736
1736
f"Ignoring bad cell_measures attribute: { attrs_or_encoding ['cell_measures' ]} " ,
1737
1737
UserWarning ,
1738
1738
)
@@ -1764,7 +1764,7 @@ def get_associated_variable_names(
1764
1764
missing = set (allvars ) - set (self ._maybe_to_dataset ()._variables )
1765
1765
if missing :
1766
1766
if OPTIONS ["warn_on_missing_variables" ]:
1767
- warnings . warn (
1767
+ emit_user_level_warning (
1768
1768
f"Variables { missing !r} not found in object but are referred to in the CF attributes." ,
1769
1769
UserWarning ,
1770
1770
)
@@ -1877,7 +1877,7 @@ def get_renamer_and_conflicts(keydict):
1877
1877
1878
1878
# Rename and warn
1879
1879
if conflicts :
1880
- warnings . warn (
1880
+ emit_user_level_warning (
1881
1881
"Conflicting variables skipped:\n "
1882
1882
+ "\n " .join (
1883
1883
[
@@ -2585,10 +2585,12 @@ def decode_vertical_coords(self, *, outnames=None, prefix=None):
2585
2585
try :
2586
2586
zname = outnames [dim ]
2587
2587
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
2589
2591
2590
2592
else :
2591
- warnings . warn (
2593
+ emit_user_level_warning (
2592
2594
"`prefix` is being deprecated; use `outnames` instead." ,
2593
2595
DeprecationWarning ,
2594
2596
)
0 commit comments