Skip to content

Apply assorted ruff/Pylint rules (PL) / Enforce PLE rules #10366

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 6 commits into from
May 29, 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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ extend-select = [
"PERF", # Perflint
"W", # pycodestyle warnings
"PGH", # pygrep-hooks
"PLE", # Pylint Errors
"UP", # pyupgrade
"FURB", # refurb
"RUF",
Expand Down
7 changes: 3 additions & 4 deletions xarray/backends/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,10 @@ def add(self, source, target, region=None):
self.sources.append(source)
self.targets.append(target)
self.regions.append(region)
elif region:
target[region] = source
else:
if region:
target[region] = source
else:
target[...] = source
target[...] = source

def sync(self, compute=True, chunkmanager_store_kwargs=None):
if self.sources:
Expand Down
36 changes: 16 additions & 20 deletions xarray/coding/cftime_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,9 +279,8 @@ def _adjust_n_years(other, n, month, reference_day):
if n > 0:
if other.month < month or (other.month == month and other.day < reference_day):
n -= 1
else:
if other.month > month or (other.month == month and other.day > reference_day):
n += 1
elif other.month > month or (other.month == month and other.day > reference_day):
n += 1
return n


Expand Down Expand Up @@ -353,12 +352,11 @@ def roll_qtrday(
# pretend to roll back if on same month but
# before compare_day
n -= 1
else:
if months_since > 0 or (
months_since == 0 and other.day > _get_day_of_month(other, day_option)
):
# make sure to roll forward, so negate
n += 1
elif months_since > 0 or (
months_since == 0 and other.day > _get_day_of_month(other, day_option)
):
# make sure to roll forward, so negate
n += 1
return n


Expand Down Expand Up @@ -815,13 +813,12 @@ def delta_to_tick(delta: timedelta | pd.Timedelta) -> Tick:
return Minute(n=seconds // 60)
else:
return Second(n=seconds)
# Regardless of the days and seconds this will always be a Millisecond
# or Microsecond object
elif delta.microseconds % 1_000 == 0:
return Millisecond(n=delta.microseconds // 1_000)
else:
# Regardless of the days and seconds this will always be a Millisecond
# or Microsecond object
if delta.microseconds % 1_000 == 0:
return Millisecond(n=delta.microseconds // 1_000)
else:
return Microsecond(n=delta.microseconds)
return Microsecond(n=delta.microseconds)


def to_cftime_datetime(date_str_or_date, calendar=None):
Expand Down Expand Up @@ -1615,11 +1612,10 @@ def date_range_like(source, calendar, use_cftime=None):
source_calendar = "standard"
source_start = default_precision_timestamp(source_start)
source_end = default_precision_timestamp(source_end)
else:
if isinstance(source, CFTimeIndex):
source_calendar = source.calendar
else: # DataArray
source_calendar = source.dt.calendar
elif isinstance(source, CFTimeIndex):
source_calendar = source.calendar
else: # DataArray
source_calendar = source.dt.calendar

if calendar == source_calendar and is_np_datetime_like(source.dtype) ^ use_cftime:
return source
Expand Down
5 changes: 2 additions & 3 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,9 +579,8 @@ def decode_cf_datetime(
"'time_unit' or specify 'use_cftime=True'.",
SerializationWarning,
)
else:
if _is_standard_calendar(calendar):
dates = cftime_to_nptime(dates, time_unit=time_unit)
elif _is_standard_calendar(calendar):
dates = cftime_to_nptime(dates, time_unit=time_unit)
elif use_cftime:
dates = _decode_datetime_with_cftime(flat_num_dates, units, calendar)
else:
Expand Down
28 changes: 13 additions & 15 deletions xarray/computation/apply_ufunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,17 +445,16 @@ def apply_dict_of_variables_vfunc(
core_dim_present = _check_core_dims(signature, variable_args, name)
if core_dim_present is True:
result_vars[name] = func(*variable_args)
elif on_missing_core_dim == "raise":
raise ValueError(core_dim_present)
elif on_missing_core_dim == "copy":
result_vars[name] = variable_args[0]
elif on_missing_core_dim == "drop":
pass
else:
if on_missing_core_dim == "raise":
raise ValueError(core_dim_present)
elif on_missing_core_dim == "copy":
result_vars[name] = variable_args[0]
elif on_missing_core_dim == "drop":
pass
else:
raise ValueError(
f"Invalid value for `on_missing_core_dim`: {on_missing_core_dim!r}"
)
raise ValueError(
f"Invalid value for `on_missing_core_dim`: {on_missing_core_dim!r}"
)

if signature.num_outputs > 1:
return _unpack_dict_tuples(result_vars, signature.num_outputs)
Expand Down Expand Up @@ -809,11 +808,10 @@ def func(*arrays):
raise ValueError(
f"unknown setting for chunked array handling in apply_ufunc: {dask}"
)
else:
if vectorize:
func = _vectorize(
func, signature, output_dtypes=output_dtypes, exclude_dims=exclude_dims
)
elif vectorize:
func = _vectorize(
func, signature, output_dtypes=output_dtypes, exclude_dims=exclude_dims
)

result_data = func(*input_data)

Expand Down
21 changes: 10 additions & 11 deletions xarray/computation/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -1253,18 +1253,17 @@ def wrapped_func(
for c, v in self.obj.coords.items():
if c == self.obj.name:
coords[c] = reduced
elif any(d in self.windows for d in v.dims):
coords[c] = v.variable.coarsen(
self.windows,
self.coord_func[c],
self.boundary,
self.side,
keep_attrs,
**kwargs,
)
else:
if any(d in self.windows for d in v.dims):
coords[c] = v.variable.coarsen(
self.windows,
self.coord_func[c],
self.boundary,
self.side,
keep_attrs,
**kwargs,
)
else:
coords[c] = v
coords[c] = v
return DataArray(
reduced, dims=self.obj.dims, coords=coords, name=self.obj.name
)
Expand Down
21 changes: 10 additions & 11 deletions xarray/conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,17 +226,16 @@ def decode_cf_variable(
DeprecationWarning,
)
decode_times = CFDatetimeCoder(use_cftime=use_cftime)
else:
if use_cftime is not None:
raise TypeError(
"Usage of 'use_cftime' as a kwarg is not allowed "
"if a 'CFDatetimeCoder' instance is passed to "
"'decode_times'. Please set 'use_cftime' "
"when initializing 'CFDatetimeCoder' instead.\n"
"Example usage:\n"
" time_coder = xr.coders.CFDatetimeCoder(use_cftime=True)\n"
" ds = xr.open_dataset(decode_times=time_coder)\n",
)
elif use_cftime is not None:
raise TypeError(
"Usage of 'use_cftime' as a kwarg is not allowed "
"if a 'CFDatetimeCoder' instance is passed to "
"'decode_times'. Please set 'use_cftime' "
"when initializing 'CFDatetimeCoder' instead.\n"
"Example usage:\n"
" time_coder = xr.coders.CFDatetimeCoder(use_cftime=True)\n"
" ds = xr.open_dataset(decode_times=time_coder)\n",
)
var = decode_times.decode(var, name=name)

if decode_endianness and not var.dtype.isnative:
Expand Down
139 changes: 66 additions & 73 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2904,9 +2904,8 @@ def sel(
for k, v in query_results.variables.items():
if v.dims:
no_scalar_variables[k] = v
else:
if k in self._coord_names:
query_results.drop_coords.append(k)
elif k in self._coord_names:
query_results.drop_coords.append(k)
query_results.variables = no_scalar_variables

result = self.isel(indexers=query_results.dim_indexers, drop=drop)
Expand Down Expand Up @@ -4552,26 +4551,25 @@ def expand_dims(
for d, c in zip_axis_dim:
all_dims.insert(d, c)
variables[k] = v.set_dims(dict(all_dims))
else:
if k not in variables:
if k in coord_names and create_index_for_new_dim:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
index, index_vars = create_default_index_implicit(v.set_dims(k))
indexes[k] = index
variables.update(index_vars)
else:
if create_index_for_new_dim:
warnings.warn(
f"No index created for dimension {k} because variable {k} is not a coordinate. "
f"To create an index for {k}, please first call `.set_coords('{k}')` on this object.",
UserWarning,
stacklevel=2,
)
elif k not in variables:
if k in coord_names and create_index_for_new_dim:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
index, index_vars = create_default_index_implicit(v.set_dims(k))
indexes[k] = index
variables.update(index_vars)
else:
if create_index_for_new_dim:
warnings.warn(
f"No index created for dimension {k} because variable {k} is not a coordinate. "
f"To create an index for {k}, please first call `.set_coords('{k}')` on this object.",
UserWarning,
stacklevel=2,
)

# create 1D variable without creating a new index
new_1d_var = v.set_dims(k)
variables.update({k: new_1d_var})
# create 1D variable without creating a new index
new_1d_var = v.set_dims(k)
variables.update({k: new_1d_var})

return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
Expand Down Expand Up @@ -4890,9 +4888,8 @@ def set_xindex(
index_cls = PandasIndex
else:
index_cls = PandasMultiIndex
else:
if not issubclass(index_cls, Index):
raise TypeError(f"{index_cls} is not a subclass of xarray.Index")
elif not issubclass(index_cls, Index):
raise TypeError(f"{index_cls} is not a subclass of xarray.Index")

invalid_coords = set(coord_names) - self._coord_names

Expand Down Expand Up @@ -6744,34 +6741,33 @@ def reduce(
if name in self.coords:
if not reduce_dims:
variables[name] = var
else:
if (
# Some reduction functions (e.g. std, var) need to run on variables
# that don't have the reduce dims: PR5393
not is_extension_array_dtype(var.dtype)
and (
not reduce_dims
or not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
)
):
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
# keep single-element dims as list, to support Hashables
reduce_maybe_single = (
None
if len(reduce_dims) == var.ndim and var.ndim != 1
else reduce_dims
)
variables[name] = var.reduce(
func,
dim=reduce_maybe_single,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)
elif (
# Some reduction functions (e.g. std, var) need to run on variables
# that don't have the reduce dims: PR5393
not is_extension_array_dtype(var.dtype)
and (
not reduce_dims
or not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
)
):
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
# keep single-element dims as list, to support Hashables
reduce_maybe_single = (
None
if len(reduce_dims) == var.ndim and var.ndim != 1
else reduce_dims
)
variables[name] = var.reduce(
func,
dim=reduce_maybe_single,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)

coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self._indexes.items() if k in variables}
Expand Down Expand Up @@ -7970,8 +7966,6 @@ def sortby(
variables = variables(self)
if not isinstance(variables, list):
variables = [variables]
else:
variables = variables
arrays = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *arrays, join="left")
aligned_self = cast("Self", aligned_vars[0])
Expand Down Expand Up @@ -8395,25 +8389,24 @@ def _integrate_one(self, coord, datetime_unit=None, cumulative=False):
if dim not in v.dims or cumulative:
variables[k] = v
coord_names.add(k)
else:
if k in self.data_vars and dim in v.dims:
coord_data = to_like_array(coord_var.data, like=v.data)
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
if cumulative:
integ = duck_array_ops.cumulative_trapezoid(
v.data, coord_data, axis=v.get_axis_num(dim)
)
v_dims = v.dims
else:
integ = duck_array_ops.trapz(
v.data, coord_data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
elif k in self.data_vars and dim in v.dims:
coord_data = to_like_array(coord_var.data, like=v.data)
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
if cumulative:
integ = duck_array_ops.cumulative_trapezoid(
v.data, coord_data, axis=v.get_axis_num(dim)
)
v_dims = v.dims
else:
variables[k] = v
integ = duck_array_ops.trapz(
v.data, coord_data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
else:
variables[k] = v
indexes = {k: v for k, v in self._indexes.items() if k in variables}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
Expand Down
Loading
Loading