File tree Expand file tree Collapse file tree 2 files changed +45
-10
lines changed Expand file tree Collapse file tree 2 files changed +45
-10
lines changed Original file line number Diff line number Diff line change @@ -1409,6 +1409,23 @@ def test_cf_standard_name_table_version():
1409
1409
assert expected_info == actual_info
1410
1410
1411
1411
1412
+ def test_add_canonical_attributes_0_dim ():
1413
+ """test if works for variables with 0 dimension"""
1414
+ xr .DataArray (
1415
+ 0 , attrs = {"standard_name" : "sea_water_potential_temperature" }
1416
+ ).cf .add_canonical_attributes ()
1417
+
1418
+
1419
+ def test_datetime_like ():
1420
+ """test for 0 or >= 2 time dimensions"""
1421
+ da = xr .DataArray (
1422
+ np .timedelta64 (1 , "D" ),
1423
+ attrs = {"standard_name" : "sea_water_age_since_surface_contact" },
1424
+ )
1425
+ new_attrs = da .cf .add_canonical_attributes ().attrs
1426
+ assert "units" not in new_attrs and "description" in new_attrs
1427
+
1428
+
1412
1429
@pytest .mark .parametrize ("override" , [True , False ])
1413
1430
@pytest .mark .parametrize ("skip" , ["units" , None ])
1414
1431
@pytest .mark .parametrize ("verbose" , [True , False ])
Original file line number Diff line number Diff line change 3
3
from typing import Any , Dict , Iterable
4
4
from xml .etree import ElementTree
5
5
6
+ import numpy as np
6
7
from xarray import DataArray
7
8
9
+ try :
10
+ import cftime
11
+ except ImportError :
12
+ cftime = None
13
+
14
+
15
+ def _contains_cftime_datetimes (array ) -> bool :
16
+ """Check if an array contains cftime.datetime objects"""
17
+ # Copied / adapted from xarray.core.common
18
+ from xarray .core .pycompat import is_duck_dask_array
19
+
20
+ if cftime is None :
21
+ return False
22
+ else :
23
+ if array .dtype == np .dtype ("O" ) and array .size > 0 :
24
+ sample = array .ravel ()[0 ]
25
+ if is_duck_dask_array (sample ):
26
+ sample = sample .compute ()
27
+ if isinstance (sample , np .ndarray ):
28
+ sample = sample .item ()
29
+ return isinstance (sample , cftime .datetime )
30
+ else :
31
+ return False
8
32
9
- def _is_datetime_like (da : DataArray ) -> bool :
10
- import numpy as np
11
33
34
+ def _is_datetime_like (da : DataArray ) -> bool :
12
35
if np .issubdtype (da .dtype , np .datetime64 ) or np .issubdtype (
13
36
da .dtype , np .timedelta64
14
37
):
15
38
return True
16
-
17
- try :
18
- import cftime
19
-
20
- if isinstance (da .data [0 ], cftime .datetime ):
21
- return True
22
- except ImportError :
23
- pass
39
+ # if cftime was not imported, _contains_cftime_datetimes will return False
40
+ if _contains_cftime_datetimes (da .data ):
41
+ return True
24
42
25
43
return False
26
44
You can’t perform that action at this time.
0 commit comments