Skip to content

Commit

Permalink
Merge branch 'main' into nanoseconds-resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
kmuehlbauer authored Sep 7, 2023
2 parents 06ed4bf + e2b6f34 commit 5e4a5ee
Show file tree
Hide file tree
Showing 24 changed files with 89 additions and 97 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
# Bookend python versions
python-version: ["3.9", "3.10", "3.11"]
python-version: ["3.9", "3.11"]
env: [""]
include:
# Minimum python version:
Expand Down
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ repos:
files: ^xarray/
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: 'v0.0.282'
rev: 'v0.0.287'
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -35,7 +35,7 @@ repos:
additional_dependencies: ["black==23.7.0"]
- id: blackdoc-autoupdate-black
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
rev: v1.5.1
hooks:
- id: mypy
# Copied from setup.cfg
Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,8 +1056,8 @@ def open_mfdataset(
)
else:
raise ValueError(
"{} is an invalid option for the keyword argument"
" ``combine``".format(combine)
f"{combine} is an invalid option for the keyword argument"
" ``combine``"
)
except ValueError:
for ds in datasets:
Expand Down
8 changes: 4 additions & 4 deletions xarray/coding/cftime_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def __init__(self, n: int = 1):
if not isinstance(n, int):
raise TypeError(
"The provided multiple 'n' must be an integer. "
"Instead a value of type {!r} was provided.".format(type(n))
f"Instead a value of type {type(n)!r} was provided."
)
self.n = n

Expand Down Expand Up @@ -353,13 +353,13 @@ def _validate_month(month, default_month):
raise TypeError(
"'self.month' must be an integer value between 1 "
"and 12. Instead, it was set to a value of "
"{!r}".format(result_month)
f"{result_month!r}"
)
elif not (1 <= result_month <= 12):
raise ValueError(
"'self.month' must be an integer value between 1 "
"and 12. Instead, it was set to a value of "
"{!r}".format(result_month)
f"{result_month!r}"
)
return result_month

Expand Down Expand Up @@ -771,7 +771,7 @@ def to_cftime_datetime(date_str_or_date, calendar=None):
raise TypeError(
"date_str_or_date must be a string or a "
"subclass of cftime.datetime. Instead got "
"{!r}.".format(date_str_or_date)
f"{date_str_or_date!r}."
)


Expand Down
11 changes: 5 additions & 6 deletions xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ def assert_all_valid_date_type(data):
if not isinstance(sample, cftime.datetime):
raise TypeError(
"CFTimeIndex requires cftime.datetime "
"objects. Got object of {}.".format(date_type)
f"objects. Got object of {date_type}."
)
if not all(isinstance(value, date_type) for value in data):
raise TypeError(
"CFTimeIndex requires using datetime "
"objects of all the same type. Got\n{}.".format(data)
f"objects of all the same type. Got\n{data}."
)


Expand Down Expand Up @@ -553,8 +553,7 @@ def shift(self, n: int | float, freq: str | timedelta):
return self + n * to_offset(freq)
else:
raise TypeError(
"'freq' must be of type "
"str or datetime.timedelta, got {}.".format(freq)
"'freq' must be of type " f"str or datetime.timedelta, got {freq}."
)

def __add__(self, other):
Expand Down Expand Up @@ -636,10 +635,10 @@ def to_datetimeindex(self, unsafe=False):
if calendar not in _STANDARD_CALENDARS and not unsafe:
warnings.warn(
"Converting a CFTimeIndex with dates from a non-standard "
"calendar, {!r}, to a pandas.DatetimeIndex, which uses dates "
f"calendar, {calendar!r}, to a pandas.DatetimeIndex, which uses dates "
"from the standard calendar. This may lead to subtle errors "
"in operations that depend on the length of time between "
"dates.".format(calendar),
"dates.",
RuntimeWarning,
stacklevel=2,
)
Expand Down
6 changes: 3 additions & 3 deletions xarray/coding/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ def encode(self, variable, name=None):
if contains_unicode and (encode_as_char or not self.allows_unicode):
if "_FillValue" in attrs:
raise NotImplementedError(
"variable {!r} has a _FillValue specified, but "
f"variable {name!r} has a _FillValue specified, but "
"_FillValue is not yet supported on unicode strings: "
"https://github.com/pydata/xarray/issues/1647".format(name)
"https://github.com/pydata/xarray/issues/1647"
)

string_encoding = encoding.pop("_Encoding", "utf-8")
Expand Down Expand Up @@ -176,7 +176,7 @@ def char_to_bytes(arr):
if len(arr.chunks[-1]) > 1:
raise ValueError(
"cannot stacked dask character array with "
"multiple chunks in the last dimension: {}".format(arr)
f"multiple chunks in the last dimension: {arr}"
)

dtype = np.dtype("S" + str(arr.shape[-1]))
Expand Down
14 changes: 6 additions & 8 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ def _decode_datetime_with_pandas(
) -> np.ndarray:
if not _is_standard_calendar(calendar):
raise OutOfBoundsDatetime(
"Cannot decode times from a non-standard calendar, {!r}, using "
"pandas.".format(calendar)
f"Cannot decode times from a non-standard calendar, {calendar!r}, using "
"pandas."
)

delta, ref_date = _unpack_netcdf_time_units(units)
Expand Down Expand Up @@ -470,8 +470,8 @@ def cftime_to_nptime(times, raise_on_invalid: bool = True) -> np.ndarray:
except ValueError as e:
if raise_on_invalid:
raise ValueError(
"Cannot convert date {} to a date in the "
"standard calendar. Reason: {}.".format(t, e)
f"Cannot convert date {t} to a date in the "
f"standard calendar. Reason: {e}."
)
else:
dt = "NaT"
Expand Down Expand Up @@ -503,10 +503,8 @@ def convert_times(times, date_type, raise_on_invalid: bool = True) -> np.ndarray
except ValueError as e:
if raise_on_invalid:
raise ValueError(
"Cannot convert date {} to a date in the "
"{} calendar. Reason: {}.".format(
t, date_type(2000, 1, 1).calendar, e
)
f"Cannot convert date {t} to a date in the "
f"{date_type(2000, 1, 1).calendar} calendar. Reason: {e}."
)
else:
dt = np.NaN
Expand Down
4 changes: 2 additions & 2 deletions xarray/coding/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,10 @@ def safe_setitem(dest, key: Hashable, value, name: T_Name = None):
if key in dest:
var_str = f" on variable {name!r}" if name else ""
raise ValueError(
"failed to prevent overwriting existing key {} in attrs{}. "
f"failed to prevent overwriting existing key {key} in attrs{var_str}. "
"This is probably an encoding field used by xarray to describe "
"how a variable is serialized. To proceed, remove this key from "
"the variable's attributes manually.".format(key, var_str)
"the variable's attributes manually."
)
dest[key] = value

Expand Down
18 changes: 8 additions & 10 deletions xarray/conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,18 @@ def _infer_dtype(array, name: T_Name = None) -> np.dtype:
return dtype

raise ValueError(
"unable to infer dtype on variable {!r}; xarray "
"cannot serialize arbitrary Python objects".format(name)
f"unable to infer dtype on variable {name!r}; xarray "
"cannot serialize arbitrary Python objects"
)


def ensure_not_multiindex(var: Variable, name: T_Name = None) -> None:
if isinstance(var, IndexVariable) and isinstance(var.to_index(), pd.MultiIndex):
raise NotImplementedError(
"variable {!r} is a MultiIndex, which cannot yet be "
f"variable {name!r} is a MultiIndex, which cannot yet be "
"serialized to netCDF files. Instead, either use reset_index() "
"to convert MultiIndex levels into coordinate variables instead "
"or use https://cf-xarray.readthedocs.io/en/latest/coding.html.".format(
name
)
"or use https://cf-xarray.readthedocs.io/en/latest/coding.html."
)


Expand All @@ -114,11 +112,11 @@ def ensure_dtype_not_object(var: Variable, name: T_Name = None) -> Variable:

if is_duck_dask_array(data):
warnings.warn(
"variable {} has data in the form of a dask array with "
f"variable {name} has data in the form of a dask array with "
"dtype=object, which means it is being loaded into memory "
"to determine a data type that can be safely stored on disk. "
"To avoid this, coerce this variable to a fixed-size dtype "
"with astype() before saving it.".format(name),
"with astype() before saving it.",
SerializationWarning,
)
data = data.compute()
Expand Down Expand Up @@ -635,9 +633,9 @@ def _encode_coordinates(variables, attributes, non_dim_coord_names):
for name in list(non_dim_coord_names):
if isinstance(name, str) and " " in name:
warnings.warn(
"coordinate {!r} has a space in its name, which means it "
f"coordinate {name!r} has a space in its name, which means it "
"cannot be marked as a coordinate on disk and will be "
"saved as a data variable instead".format(name),
"saved as a data variable instead",
SerializationWarning,
stacklevel=6,
)
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ def is_alignable(obj):
elif raise_on_invalid:
raise ValueError(
"object to align is neither an xarray.Dataset, "
"an xarray.DataArray nor a dictionary: {!r}".format(variables)
f"an xarray.DataArray nor a dictionary: {variables!r}"
)
else:
out.append(variables)
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):

if ufunc.signature is not None:
raise NotImplementedError(
"{} not supported: xarray objects do not directly implement "
f"{ufunc} not supported: xarray objects do not directly implement "
"generalized ufuncs. Instead, use xarray.apply_ufunc or "
"explicitly convert to xarray objects to NumPy arrays "
"(e.g., with `.values`).".format(ufunc)
"(e.g., with `.values`)."
)

if method != "__call__":
Expand Down
12 changes: 5 additions & 7 deletions xarray/core/combine.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ def _infer_concat_order_from_coords(datasets):
ascending = False
else:
raise ValueError(
"Coordinate variable {} is neither "
f"Coordinate variable {dim} is neither "
"monotonically increasing nor "
"monotonically decreasing on all datasets".format(dim)
"monotonically decreasing on all datasets"
)

# Assume that any two datasets whose coord along dim starts
Expand Down Expand Up @@ -221,10 +221,8 @@ def _combine_nd(
n_dims = len(example_tile_id)
if len(concat_dims) != n_dims:
raise ValueError(
"concat_dims has length {} but the datasets "
"passed are nested in a {}-dimensional structure".format(
len(concat_dims), n_dims
)
f"concat_dims has length {len(concat_dims)} but the datasets "
f"passed are nested in a {n_dims}-dimensional structure"
)

# Each iteration of this loop reduces the length of the tile_ids tuples
Expand Down Expand Up @@ -646,7 +644,7 @@ def _combine_single_variable_hypercube(
if not (indexes.is_monotonic_increasing or indexes.is_monotonic_decreasing):
raise ValueError(
"Resulting object does not have monotonic"
" global indexes along dimension {}".format(dim)
f" global indexes along dimension {dim}"
)

return concatenated
Expand Down
6 changes: 3 additions & 3 deletions xarray/core/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,7 @@ def cov(
if any(not isinstance(arr, DataArray) for arr in [da_a, da_b]):
raise TypeError(
"Only xr.DataArray is supported."
"Given {}.".format([type(arr) for arr in [da_a, da_b]])
f"Given {[type(arr) for arr in [da_a, da_b]]}."
)

return _cov_corr(da_a, da_b, dim=dim, ddof=ddof, method="cov")
Expand Down Expand Up @@ -1364,7 +1364,7 @@ def corr(da_a: T_DataArray, da_b: T_DataArray, dim: Dims = None) -> T_DataArray:
if any(not isinstance(arr, DataArray) for arr in [da_a, da_b]):
raise TypeError(
"Only xr.DataArray is supported."
"Given {}.".format([type(arr) for arr in [da_a, da_b]])
f"Given {[type(arr) for arr in [da_a, da_b]]}."
)

return _cov_corr(da_a, da_b, dim=dim, method="corr")
Expand Down Expand Up @@ -1707,7 +1707,7 @@ def dot(
if any(not isinstance(arr, (Variable, DataArray)) for arr in arrays):
raise TypeError(
"Only xr.DataArray and xr.Variable are supported."
"Given {}.".format([type(arr) for arr in arrays])
f"Given {[type(arr) for arr in arrays]}."
)

if len(arrays) == 0:
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def to_index(self, ordered_dims: Sequence[Hashable] | None = None) -> pd.Index:
elif set(ordered_dims) != set(self.dims):
raise ValueError(
"ordered_dims must match dims, but does not: "
"{} vs {}".format(ordered_dims, self.dims)
f"{ordered_dims} vs {self.dims}"
)

if len(ordered_dims) == 0:
Expand Down
8 changes: 3 additions & 5 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2234,8 +2234,7 @@ def interp(
"""
if self.dtype.kind not in "uifc":
raise TypeError(
"interp only works for a numeric type array. "
"Given {}.".format(self.dtype)
"interp only works for a numeric type array. " f"Given {self.dtype}."
)
ds = self._to_temp_dataset().interp(
coords,
Expand Down Expand Up @@ -2362,8 +2361,7 @@ def interp_like(
"""
if self.dtype.kind not in "uifc":
raise TypeError(
"interp only works for a numeric type array. "
"Given {}.".format(self.dtype)
"interp only works for a numeric type array. " f"Given {self.dtype}."
)
ds = self._to_temp_dataset().interp_like(
other, method=method, kwargs=kwargs, assume_sorted=assume_sorted
Expand Down Expand Up @@ -4325,7 +4323,7 @@ def from_dict(cls: type[T_DataArray], d: Mapping[str, Any]) -> T_DataArray:
except KeyError as e:
raise ValueError(
"cannot convert dict when coords are missing the key "
"'{dims_data}'".format(dims_data=str(e.args[0]))
f"'{str(e.args[0])}'"
)
try:
data = d["data"]
Expand Down
Loading

0 comments on commit 5e4a5ee

Please sign in to comment.