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 ,
@@ -107,7 +108,7 @@ def apply_mapper(
107
108
"""
108
109
109
110
if not isinstance (key , Hashable ):
110
- if default is None :
111
+ if default is None : # type: ignore[unreachable]
111
112
raise ValueError (
112
113
"`default` must be provided when `key` is not not a valid DataArray name (of hashable type)."
113
114
)
@@ -224,7 +225,7 @@ def _get_custom_criteria(
224
225
try :
225
226
from regex import match as regex_match
226
227
except ImportError :
227
- from re import match as regex_match # type: ignore
228
+ from re import match as regex_match # type: ignore[no-redef]
228
229
229
230
if isinstance (obj , DataArray ):
230
231
obj = obj ._to_temp_dataset ()
@@ -363,8 +364,6 @@ def _get_measure(obj: DataArray | Dataset, key: str) -> list[str]:
363
364
if key in measures :
364
365
results .update ([measures [key ]])
365
366
366
- if isinstance (results , str ):
367
- return [results ]
368
367
return list (results )
369
368
370
369
@@ -471,7 +470,7 @@ def _get_all(obj: DataArray | Dataset, key: Hashable) -> list[Hashable]:
471
470
"""
472
471
all_mappers : tuple [Mapper ] = (
473
472
_get_custom_criteria ,
474
- functools .partial (_get_custom_criteria , criteria = cf_role_criteria ), # type: ignore
473
+ functools .partial (_get_custom_criteria , criteria = cf_role_criteria ), # type: ignore[assignment]
475
474
functools .partial (_get_custom_criteria , criteria = grid_mapping_var_criteria ),
476
475
_get_axis_coord ,
477
476
_get_measure ,
@@ -653,10 +652,10 @@ def _getattr(
653
652
):
654
653
raise AttributeError (
655
654
f"{ obj .__class__ .__name__ + '.cf' !r} object has no attribute { attr !r} "
656
- )
655
+ ) from None
657
656
raise AttributeError (
658
657
f"{ attr !r} is not a valid attribute on the underlying xarray object."
659
- )
658
+ ) from None
660
659
661
660
if isinstance (attribute , Mapping ):
662
661
if not attribute :
@@ -680,7 +679,7 @@ def _getattr(
680
679
newmap .update (dict .fromkeys (inverted [key ], value ))
681
680
newmap .update ({key : attribute [key ] for key in unused_keys })
682
681
683
- skip : dict [str , list [Hashable ] | None ] = {
682
+ skip : dict [str , list [Literal [ "coords" , "measures" ] ] | None ] = {
684
683
"data_vars" : ["coords" ],
685
684
"coords" : None ,
686
685
}
@@ -689,7 +688,7 @@ def _getattr(
689
688
newmap [key ] = _getitem (accessor , key , skip = skip [attr ])
690
689
return newmap
691
690
692
- elif isinstance (attribute , Callable ): # type: ignore
691
+ elif isinstance (attribute , Callable ): # type: ignore[arg-type]
693
692
func : Callable = attribute
694
693
695
694
else :
@@ -721,7 +720,7 @@ def wrapper(*args, **kwargs):
721
720
def _getitem (
722
721
accessor : CFAccessor ,
723
722
key : Hashable ,
724
- skip : list [Hashable ] | None = None ,
723
+ skip : list [Literal [ "coords" , "measures" ] ] | None = None ,
725
724
) -> DataArray :
726
725
...
727
726
@@ -730,15 +729,15 @@ def _getitem(
730
729
def _getitem (
731
730
accessor : CFAccessor ,
732
731
key : Iterable [Hashable ],
733
- skip : list [Hashable ] | None = None ,
732
+ skip : list [Literal [ "coords" , "measures" ] ] | None = None ,
734
733
) -> Dataset :
735
734
...
736
735
737
736
738
737
def _getitem (
739
- accessor ,
740
- key ,
741
- skip = None ,
738
+ accessor : CFAccessor ,
739
+ key : Hashable | Iterable [ Hashable ] ,
740
+ skip : list [ Literal [ "coords" , "measures" ]] | None = None ,
742
741
):
743
742
"""
744
743
Index into obj using key. Attaches CF associated variables.
@@ -789,7 +788,7 @@ def check_results(names, key):
789
788
measures = accessor ._get_all_cell_measures ()
790
789
except ValueError :
791
790
measures = []
792
- warnings . warn ("Ignoring bad cell_measures attribute." , UserWarning )
791
+ emit_user_level_warning ("Ignoring bad cell_measures attribute." , UserWarning )
793
792
794
793
if isinstance (obj , Dataset ):
795
794
grid_mapping_names = list (accessor .grid_mapping_names )
@@ -852,6 +851,7 @@ def check_results(names, key):
852
851
)
853
852
coords .extend (itertools .chain (* extravars .values ()))
854
853
854
+ ds : Dataset
855
855
if isinstance (obj , DataArray ):
856
856
ds = obj ._to_temp_dataset ()
857
857
else :
@@ -860,7 +860,7 @@ def check_results(names, key):
860
860
if scalar_key :
861
861
if len (allnames ) == 1 :
862
862
(name ,) = allnames
863
- da : DataArray = ds .reset_coords ()[name ] # type: ignore
863
+ da : DataArray = ds .reset_coords ()[name ]
864
864
if name in coords :
865
865
coords .remove (name )
866
866
for k1 in coords :
@@ -877,26 +877,27 @@ def check_results(names, key):
877
877
878
878
ds = ds .reset_coords ()[varnames + coords ]
879
879
if isinstance (obj , DataArray ):
880
- if scalar_key and len (ds .variables ) == 1 :
881
- # single dimension coordinates
882
- assert coords
883
- assert not varnames
880
+ if scalar_key :
881
+ if len (ds .variables ) == 1 : # type: ignore[unreachable]
882
+ # single dimension coordinates
883
+ assert coords
884
+ assert not varnames
884
885
885
- return ds [coords [0 ]]
886
+ return ds [coords [0 ]]
886
887
887
- elif scalar_key and len ( ds . variables ) > 1 :
888
- raise NotImplementedError (
889
- "Not sure what to return when given scalar key for DataArray and it has multiple values. "
890
- "Please open an issue."
891
- )
888
+ else :
889
+ raise NotImplementedError (
890
+ "Not sure what to return when given scalar key for DataArray and it has multiple values. "
891
+ "Please open an issue."
892
+ )
892
893
893
894
return ds .set_coords (coords )
894
895
895
896
except KeyError :
896
897
raise KeyError (
897
898
f"{ kind } .cf does not understand the key { k !r} . "
898
899
f"Use 'repr({ kind } .cf)' (or '{ kind } .cf' in a Jupyter environment) to see a list of key names that can be interpreted."
899
- )
900
+ ) from None
900
901
901
902
902
903
def _possible_x_y_plot (obj , key , skip = None ):
@@ -1135,7 +1136,7 @@ def _assert_valid_other_comparison(self, other):
1135
1136
)
1136
1137
return flag_dict
1137
1138
1138
- def __eq__ (self , other ) -> DataArray : # type: ignore
1139
+ def __eq__ (self , other ) -> DataArray : # type: ignore[override]
1139
1140
"""
1140
1141
Compare flag values against ``other``.
1141
1142
@@ -1155,7 +1156,7 @@ def __eq__(self, other) -> DataArray: # type: ignore
1155
1156
"""
1156
1157
return self ._extract_flags ([other ])[other ].rename (self ._obj .name )
1157
1158
1158
- def __ne__ (self , other ) -> DataArray : # type: ignore
1159
+ def __ne__ (self , other ) -> DataArray : # type: ignore[override]
1159
1160
"""
1160
1161
Compare flag values against ``other``.
1161
1162
@@ -1328,7 +1329,7 @@ def curvefit(
1328
1329
coords_iter = coords
1329
1330
coords = [
1330
1331
apply_mapper (
1331
- [_single (_get_coords )], self ._obj , v , error = False , default = [v ] # type: ignore
1332
+ [_single (_get_coords )], self ._obj , v , error = False , default = [v ] # type: ignore[arg-type]
1332
1333
)[0 ]
1333
1334
for v in coords_iter
1334
1335
]
@@ -1339,7 +1340,7 @@ def curvefit(
1339
1340
reduce_dims_iter = list (reduce_dims )
1340
1341
reduce_dims = [
1341
1342
apply_mapper (
1342
- [_single (_get_dims )], self ._obj , v , error = False , default = [v ] # type: ignore
1343
+ [_single (_get_dims )], self ._obj , v , error = False , default = [v ] # type: ignore[arg-type]
1343
1344
)[0 ]
1344
1345
for v in reduce_dims_iter
1345
1346
]
@@ -1435,7 +1436,7 @@ def _rewrite_values(
1435
1436
1436
1437
# allow multiple return values here.
1437
1438
# these are valid for .sel, .isel, .coarsen
1438
- all_mappers = ChainMap ( # type: ignore
1439
+ all_mappers = ChainMap ( # type: ignore[misc]
1439
1440
key_mappers ,
1440
1441
dict .fromkeys (var_kws , (_get_all ,)),
1441
1442
)
@@ -1531,7 +1532,7 @@ def describe(self):
1531
1532
Print a string repr to screen.
1532
1533
"""
1533
1534
1534
- warnings . warn (
1535
+ emit_user_level_warning (
1535
1536
"'obj.cf.describe()' will be removed in a future version. "
1536
1537
"Use instead 'repr(obj.cf)' or 'obj.cf' in a Jupyter environment." ,
1537
1538
DeprecationWarning ,
@@ -1695,10 +1696,9 @@ def cell_measures(self) -> dict[str, list[Hashable]]:
1695
1696
bad_vars = list (
1696
1697
as_dataset .filter_by_attrs (cell_measures = attr ).data_vars .keys ()
1697
1698
)
1698
- warnings . warn (
1699
+ emit_user_level_warning (
1699
1700
f"Ignoring bad cell_measures attribute: { attr } on { bad_vars } ." ,
1700
1701
UserWarning ,
1701
- stacklevel = 2 ,
1702
1702
)
1703
1703
measures = {
1704
1704
key : self ._drop_missing_variables (_get_all (self ._obj , key )) for key in keys
@@ -1816,9 +1816,9 @@ def get_associated_variable_names(
1816
1816
except ValueError as e :
1817
1817
if error :
1818
1818
msg = e .args [0 ] + " Ignore this error by passing 'error=False'"
1819
- raise ValueError (msg )
1819
+ raise ValueError (msg ) from None
1820
1820
else :
1821
- warnings . warn (
1821
+ emit_user_level_warning (
1822
1822
f"Ignoring bad cell_measures attribute: { attrs_or_encoding ['cell_measures' ]} " ,
1823
1823
UserWarning ,
1824
1824
)
@@ -1850,7 +1850,7 @@ def get_associated_variable_names(
1850
1850
missing = set (allvars ) - set (self ._maybe_to_dataset ()._variables )
1851
1851
if missing :
1852
1852
if OPTIONS ["warn_on_missing_variables" ]:
1853
- warnings . warn (
1853
+ emit_user_level_warning (
1854
1854
f"Variables { missing !r} not found in object but are referred to in the CF attributes." ,
1855
1855
UserWarning ,
1856
1856
)
@@ -1963,7 +1963,7 @@ def get_renamer_and_conflicts(keydict):
1963
1963
1964
1964
# Rename and warn
1965
1965
if conflicts :
1966
- warnings . warn (
1966
+ emit_user_level_warning (
1967
1967
"Conflicting variables skipped:\n "
1968
1968
+ "\n " .join (
1969
1969
[
@@ -2684,10 +2684,12 @@ def decode_vertical_coords(self, *, outnames=None, prefix=None):
2684
2684
try :
2685
2685
zname = outnames [dim ]
2686
2686
except KeyError :
2687
- raise KeyError ("Your `outnames` need to include a key of `dim`." )
2687
+ raise KeyError (
2688
+ "Your `outnames` need to include a key of `dim`."
2689
+ ) from None
2688
2690
2689
2691
else :
2690
- warnings . warn (
2692
+ emit_user_level_warning (
2691
2693
"`prefix` is being deprecated; use `outnames` instead." ,
2692
2694
DeprecationWarning ,
2693
2695
)
0 commit comments