Skip to content

Apply assorted ruff/flake8-simplify rules (SIM) #10364

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions xarray/backends/h5netcdf_.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,16 @@ def _read_attributes(h5netcdf_var):
# bytes attributes to strings
attrs = {}
for k, v in h5netcdf_var.attrs.items():
if k not in ["_FillValue", "missing_value"]:
if isinstance(v, bytes):
try:
v = v.decode("utf-8")
except UnicodeDecodeError:
emit_user_level_warning(
f"'utf-8' codec can't decode bytes for attribute "
f"{k!r} of h5netcdf object {h5netcdf_var.name!r}, "
f"returning bytes undecoded.",
UnicodeWarning,
)
if k not in ["_FillValue", "missing_value"] and isinstance(v, bytes):
try:
v = v.decode("utf-8")
except UnicodeDecodeError:
emit_user_level_warning(
f"'utf-8' codec can't decode bytes for attribute "
f"{k!r} of h5netcdf object {h5netcdf_var.name!r}, "
f"returning bytes undecoded.",
UnicodeWarning,
)
attrs[k] = v
return attrs

Expand Down
4 changes: 1 addition & 3 deletions xarray/backends/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ def _get_lock_maker(scheduler=None):
dask.utils.get_scheduler_lock
"""

if scheduler is None:
return _get_threaded_lock
elif scheduler == "threaded":
if scheduler is None or scheduler == "threaded":
return _get_threaded_lock
elif scheduler == "multiprocessing":
return _get_multiprocessing_lock
Expand Down
9 changes: 4 additions & 5 deletions xarray/backends/netcdf3.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,10 @@ def _maybe_prepare_times(var):
data = var.data
if data.dtype.kind in "iu":
units = var.attrs.get("units", None)
if units is not None:
if coding.variables._is_time_like(units):
mask = data == np.iinfo(np.int64).min
if mask.any():
data = np.where(mask, var.attrs.get("_FillValue", np.nan), data)
if units is not None and coding.variables._is_time_like(units):
mask = data == np.iinfo(np.int64).min
if mask.any():
data = np.where(mask, var.attrs.get("_FillValue", np.nan), data)
return data


Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ def _validate_datatypes_for_zarr_append(vname, existing_var, new_var):
# in the dataset, and with dtypes which are not known to be easy-to-append, necessitate
# exact dtype equality, as checked below.
pass
elif not new_var.dtype == existing_var.dtype:
elif new_var.dtype != existing_var.dtype:
raise ValueError(
f"Mismatched dtypes for variable {vname} between Zarr store on disk "
f"and dataset to append. Store has dtype {existing_var.dtype} but "
Expand Down Expand Up @@ -1233,7 +1233,7 @@ def set_variables(self, variables, check_encoding_set, writer, unlimited_dims=No
else:
encoded_attrs[DIMENSION_KEY] = dims

encoding["overwrite"] = True if self._mode == "w" else False
encoding["overwrite"] = self._mode == "w"

zarr_array = self._create_new_array(
name=name,
Expand Down
2 changes: 1 addition & 1 deletion xarray/coding/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def get_freq(self):
return self._infer_daily_rule()
# There is no possible intraday frequency with a non-unique delta
# Different from pandas: we don't need to manage DST and business offsets in cftime
elif not len(self.deltas) == 1:
elif len(self.deltas) != 1:
return None

if _is_multiple(delta, _ONE_HOUR):
Expand Down
22 changes: 10 additions & 12 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import contextlib
import re
import warnings
from collections.abc import Callable, Hashable
Expand Down Expand Up @@ -429,12 +430,11 @@ def _check_date_is_after_shift(
# if we are outside the well-defined date range
# proleptic_gregorian and standard/gregorian are only equivalent
# if reference date and date range is >= 1582-10-15
if calendar != "proleptic_gregorian":
if date < type(date)(1582, 10, 15):
raise OutOfBoundsDatetime(
f"Dates before 1582-10-15 cannot be decoded "
f"with pandas using {calendar!r} calendar: {date}"
)
if calendar != "proleptic_gregorian" and date < type(date)(1582, 10, 15):
raise OutOfBoundsDatetime(
f"Dates before 1582-10-15 cannot be decoded "
f"with pandas using {calendar!r} calendar: {date}"
)


def _check_higher_resolution(
Expand Down Expand Up @@ -929,12 +929,10 @@ def _cleanup_netcdf_time_units(units: str) -> str:
time_units = time_units.lower()
if not time_units.endswith("s"):
time_units = f"{time_units}s"
try:
# don't worry about reifying the units if they're out of bounds or
# formatted badly
with contextlib.suppress(OutOfBoundsDatetime, ValueError):
units = f"{time_units} since {format_timestamp(ref_date)}"
except (OutOfBoundsDatetime, ValueError):
# don't worry about reifying the units if they're out of bounds or
# formatted badly
pass
return units


Expand Down Expand Up @@ -1412,7 +1410,7 @@ def decode(self, variable: Variable, name: T_Name = None) -> Variable:


def has_timedelta64_encoding_dtype(attrs_or_encoding: dict) -> bool:
dtype = attrs_or_encoding.get("dtype", None)
dtype = attrs_or_encoding.get("dtype")
return isinstance(dtype, str) and dtype.startswith("timedelta64")


Expand Down
10 changes: 4 additions & 6 deletions xarray/computation/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,8 @@ def cov(
"Only xr.DataArray is supported."
f"Given {[type(arr) for arr in [da_a, da_b]]}."
)
if weights is not None:
if not isinstance(weights, DataArray):
raise TypeError(f"Only xr.DataArray is supported. Given {type(weights)}.")
if weights is not None and not isinstance(weights, DataArray):
raise TypeError(f"Only xr.DataArray is supported. Given {type(weights)}.")
return _cov_corr(da_a, da_b, weights=weights, dim=dim, ddof=ddof, method="cov")


Expand Down Expand Up @@ -248,9 +247,8 @@ def corr(
"Only xr.DataArray is supported."
f"Given {[type(arr) for arr in [da_a, da_b]]}."
)
if weights is not None:
if not isinstance(weights, DataArray):
raise TypeError(f"Only xr.DataArray is supported. Given {type(weights)}.")
if weights is not None and not isinstance(weights, DataArray):
raise TypeError(f"Only xr.DataArray is supported. Given {type(weights)}.")
return _cov_corr(da_a, da_b, weights=weights, dim=dim, method="corr")


Expand Down
33 changes: 17 additions & 16 deletions xarray/conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def decode_cf_variable(
if isinstance(decode_times, CFDatetimeCoder):
decode_timedelta = CFTimedeltaCoder(time_unit=decode_times.time_unit)
else:
decode_timedelta = True if decode_times else False
decode_timedelta = bool(decode_times)

if concat_characters:
if stack_char_dim:
Expand Down Expand Up @@ -276,12 +276,11 @@ def _update_bounds_attributes(variables: T_Variables) -> None:
attrs = v.attrs
units = attrs.get("units")
has_date_units = isinstance(units, str) and "since" in units
if has_date_units and "bounds" in attrs:
if attrs["bounds"] in variables:
bounds_attrs = variables[attrs["bounds"]].attrs
bounds_attrs.setdefault("units", attrs["units"])
if "calendar" in attrs:
bounds_attrs.setdefault("calendar", attrs["calendar"])
if has_date_units and "bounds" in attrs and attrs["bounds"] in variables:
bounds_attrs = variables[attrs["bounds"]].attrs
bounds_attrs.setdefault("units", attrs["units"])
if "calendar" in attrs:
bounds_attrs.setdefault("calendar", attrs["calendar"])


def _update_bounds_encoding(variables: T_Variables) -> None:
Expand Down Expand Up @@ -325,12 +324,11 @@ def _update_bounds_encoding(variables: T_Variables) -> None:
f"{name} before writing to a file.",
)

if has_date_units and "bounds" in attrs:
if attrs["bounds"] in variables:
bounds_encoding = variables[attrs["bounds"]].encoding
bounds_encoding.setdefault("units", encoding["units"])
if "calendar" in encoding:
bounds_encoding.setdefault("calendar", encoding["calendar"])
if has_date_units and "bounds" in attrs and attrs["bounds"] in variables:
bounds_encoding = variables[attrs["bounds"]].encoding
bounds_encoding.setdefault("units", encoding["units"])
if "calendar" in encoding:
bounds_encoding.setdefault("calendar", encoding["calendar"])


T = TypeVar("T")
Expand Down Expand Up @@ -805,8 +803,11 @@ def cf_encoder(variables: T_Variables, attributes: T_Attrs):
"leap_year",
"month_lengths",
]:
if attr in new_vars[bounds].attrs and attr in var.attrs:
if new_vars[bounds].attrs[attr] == var.attrs[attr]:
new_vars[bounds].attrs.pop(attr)
if (
attr in new_vars[bounds].attrs
and attr in var.attrs
and new_vars[bounds].attrs[attr] == var.attrs[attr]
):
new_vars[bounds].attrs.pop(attr)

return new_vars, attributes
25 changes: 12 additions & 13 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -8141,19 +8141,18 @@ def quantile(
for name, var in self.variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
variables[name] = var.quantile(
q,
dim=reduce_dims,
method=method,
keep_attrs=keep_attrs,
skipna=skipna,
)
if name not in self.coords and (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
variables[name] = var.quantile(
q,
dim=reduce_dims,
method=method,
keep_attrs=keep_attrs,
skipna=skipna,
)

else:
variables[name] = var
Expand Down
5 changes: 2 additions & 3 deletions xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1054,9 +1054,8 @@ def diff_datatree_repr(a: DataTree, b: DataTree, compat):
f"Left and right {type(a).__name__} objects are not {_compat_to_str(compat)}"
]

if compat == "identical":
if diff_name := diff_name_summary(a, b):
summary.append(diff_name)
if compat == "identical" and (diff_name := diff_name_summary(a, b)):
summary.append(diff_name)

treestructure_diff = diff_treestructure(a, b)

Expand Down
11 changes: 5 additions & 6 deletions xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,13 +977,12 @@ def _maybe_reindex(self, combined):
indexers = {}
for grouper in self.groupers:
index = combined._indexes.get(grouper.name, None)
if has_missing_groups and index is not None:
if (has_missing_groups and index is not None) or (
len(self.groupers) > 1
and not isinstance(grouper.full_index, pd.RangeIndex)
and not index.index.equals(grouper.full_index)
):
indexers[grouper.name] = grouper.full_index
elif len(self.groupers) > 1:
if not isinstance(
grouper.full_index, pd.RangeIndex
) and not index.index.equals(grouper.full_index):
indexers[grouper.name] = grouper.full_index
if indexers:
combined = combined.reindex(**indexers)
return combined
Expand Down
11 changes: 5 additions & 6 deletions xarray/core/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,11 +364,10 @@ def interp_na(
# Convert to float
max_gap = timedelta_to_numeric(max_gap)

if not use_coordinate:
if not isinstance(max_gap, Number | np.number):
raise TypeError(
f"Expected integer or floating point max_gap since use_coordinate=False. Received {max_type}."
)
if not use_coordinate and not isinstance(max_gap, Number | np.number):
raise TypeError(
f"Expected integer or floating point max_gap since use_coordinate=False. Received {max_type}."
)

# method
index = get_clean_interp_index(self, dim, use_coordinate=use_coordinate)
Expand Down Expand Up @@ -499,7 +498,7 @@ def _get_interpolator(
# take higher dimensional data but scipy.interp1d can.
if (
method == "linear"
and not kwargs.get("fill_value") == "extrapolate"
and kwargs.get("fill_value") != "extrapolate"
and not vectorizeable_only
):
kwargs.update(method=method)
Expand Down
14 changes: 8 additions & 6 deletions xarray/core/parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,12 +363,14 @@ def _wrapper(

# check that index lengths and values are as expected
for name, index in result._indexes.items():
if name in expected["shapes"]:
if result.sizes[name] != expected["shapes"][name]:
raise ValueError(
f"Received dimension {name!r} of length {result.sizes[name]}. "
f"Expected length {expected['shapes'][name]}."
)
if (
name in expected["shapes"]
and result.sizes[name] != expected["shapes"][name]
):
raise ValueError(
f"Received dimension {name!r} of length {result.sizes[name]}. "
f"Expected length {expected['shapes'][name]}."
)

# ChainMap wants MutableMapping, but xindexes is Mapping
merged_indexes = collections.ChainMap(
Expand Down
4 changes: 1 addition & 3 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,10 +704,8 @@ def try_read_magic_number_from_path(pathlike, count=8) -> bytes | None:
def try_read_magic_number_from_file_or_path(filename_or_obj, count=8) -> bytes | None:
magic_number = try_read_magic_number_from_path(filename_or_obj, count)
if magic_number is None:
try:
with contextlib.suppress(TypeError):
magic_number = read_magic_number_from_file(filename_or_obj, count)
except TypeError:
pass
return magic_number


Expand Down
35 changes: 17 additions & 18 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,14 @@ def as_variable(
f"explicit list of dimensions: {obj!r}"
)

if auto_convert:
if name is not None and name in obj.dims and obj.ndim == 1:
# automatically convert the Variable into an Index
emit_user_level_warning(
f"variable {name!r} with name matching its dimension will not be "
"automatically converted into an `IndexVariable` object in the future.",
FutureWarning,
)
obj = obj.to_index_variable()
if auto_convert and name is not None and name in obj.dims and obj.ndim == 1:
# automatically convert the Variable into an Index
emit_user_level_warning(
f"variable {name!r} with name matching its dimension will not be "
"automatically converted into an `IndexVariable` object in the future.",
FutureWarning,
)
obj = obj.to_index_variable()

return obj

Expand Down Expand Up @@ -2930,15 +2929,15 @@ def broadcast_variables(*variables: Variable) -> tuple[Variable, ...]:


def _broadcast_compat_data(self, other):
if not OPTIONS["arithmetic_broadcast"]:
if (isinstance(other, Variable) and self.dims != other.dims) or (
is_duck_array(other) and self.ndim != other.ndim
):
raise ValueError(
"Broadcasting is necessary but automatic broadcasting is disabled via "
"global option `'arithmetic_broadcast'`. "
"Use `xr.set_options(arithmetic_broadcast=True)` to enable automatic broadcasting."
)
if not OPTIONS["arithmetic_broadcast"] and (
(isinstance(other, Variable) and self.dims != other.dims)
or (is_duck_array(other) and self.ndim != other.ndim)
):
raise ValueError(
"Broadcasting is necessary but automatic broadcasting is disabled via "
"global option `'arithmetic_broadcast'`. "
"Use `xr.set_options(arithmetic_broadcast=True)` to enable automatic broadcasting."
)

if all(hasattr(other, attr) for attr in ["dims", "data", "shape", "encoding"]):
# `other` satisfies the necessary Variable API for broadcast_variables
Expand Down
Loading
Loading