@@ -953,6 +953,35 @@ def _get_possible(accessor, criteria):
953
953
return _get_possible (obj .cf , y_criteria )
954
954
955
955
956
+ def _update_data_units (
957
+ result : DataArray | Dataset ,
958
+ source : DataArray | Dataset ,
959
+ coord_name : str ,
960
+ new_unit_template : str
961
+ ) -> DataArray | Dataset :
962
+ try :
963
+ coord_units = source [coord_name ].attrs ["units" ]
964
+ except KeyError :
965
+ return result
966
+
967
+ if isinstance (source , DataArray ):
968
+ try :
969
+ result .attrs ["units" ] = new_unit_template .format (
970
+ source .attrs ["units" ], source [coord_name ].attrs ["units" ]
971
+ )
972
+ except KeyError :
973
+ pass
974
+ else :
975
+ for name in result .data_vars :
976
+ try :
977
+ result [name ].attrs ["units" ] = new_unit_template .format (
978
+ source [name ].attrs ["units" ], coord_units
979
+ )
980
+ except KeyError :
981
+ pass
982
+ return result
983
+
984
+
956
985
class _CFWrappedClass (SupportsArithmetic ):
957
986
"""
958
987
This class is used to wrap any class in _WRAPPED_CLASSES.
@@ -2102,26 +2131,7 @@ def differentiate(
2102
2131
(_single (_get_coords ),), self ._obj , coord , error = False , default = [coord ]
2103
2132
)[0 ]
2104
2133
result = self ._obj .differentiate (coord , * xr_args , ** xr_kwargs )
2105
- if isinstance (self ._obj , DataArray ):
2106
- try :
2107
- result .attrs ["units" ] = "{:s} / ({:s})" .format (
2108
- self ._obj .attrs ["units" ], self ._obj [coord ].attrs ["units" ]
2109
- )
2110
- except KeyError :
2111
- pass
2112
- else :
2113
- try :
2114
- coord_units = self ._obj [coord ].attrs ["units" ]
2115
- except KeyError :
2116
- pass
2117
- else :
2118
- for name in result .data_vars :
2119
- try :
2120
- result [name ].attrs ["units" ] = "{:s} / ({:s})" .format (
2121
- self ._obj [name ].attrs ["units" ], coord_units
2122
- )
2123
- except KeyError :
2124
- pass
2134
+ result = _update_data_units (result , self ._obj , coord , "{:s} / ({:s})" )
2125
2135
if positive_upward :
2126
2136
coord = self ._obj [coord ]
2127
2137
attrs = coord .attrs
0 commit comments