Skip to content
Merged
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ extend-select = [
"PIE", # flake8-pie
"TID", # flake8-tidy-imports (absolute imports)
"PYI", # flake8-pyi
"SIM", # flake8-simplify
"FLY", # flynt
"I", # isort
"PERF", # Perflint
Expand All @@ -283,6 +284,11 @@ ignore = [
"PIE790", # unnecessary pass statement
"PYI019", # use `Self` instead of custom TypeVar
"PYI041", # use `float` instead of `int | float`
"SIM102", # use a single `if` statement instead of nested `if` statements
"SIM108", # use ternary operator instead of `if`-`else`-block
"SIM117", # use a single `with` statement instead of nested `with` statements
"SIM118", # use `key in dict` instead of `key in dict.keys()`
"SIM300", # yoda condition detected
"PERF203", # try-except within a loop incurs performance overhead
"E402", # module level import not at top of file
"E731", # do not assign a lambda expression, use a def
Expand Down
14 changes: 8 additions & 6 deletions xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,9 +989,10 @@ def diff_array_repr(a, b, compat):
):
summary.append(coords_diff)

if compat == "identical":
if attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat):
summary.append(attrs_diff)
if compat == "identical" and (
attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat)
):
summary.append(attrs_diff)

return "\n".join(summary)

Expand Down Expand Up @@ -1029,9 +1030,10 @@ def diff_dataset_repr(a, b, compat):
):
summary.append(data_diff)

if compat == "identical":
if attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat):
summary.append(attrs_diff)
if compat == "identical" and (
attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat)
):
summary.append(attrs_diff)

return "\n".join(summary)

Expand Down
2 changes: 1 addition & 1 deletion xarray/core/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1247,7 +1247,7 @@ def create_variables(
level = name
dtype = self.level_coords_dtype[name] # type: ignore[index] # TODO: are Hashables ok?

var = variables.get(name, None)
var = variables.get(name)
if var is not None:
attrs = var.attrs
encoding = var.encoding
Expand Down
26 changes: 10 additions & 16 deletions xarray/core/resample_cftime.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,22 +84,16 @@ def __init__(
self.freq = to_offset(freq)
self.origin = origin

if isinstance(self.freq, MonthEnd | QuarterEnd | YearEnd):
if closed is None:
self.closed = "right"
else:
self.closed = closed
if label is None:
self.label = "right"
else:
self.label = label
# The backward resample sets ``closed`` to ``'right'`` by default
# since the last value should be considered as the edge point for
# the last bin. When origin in "end" or "end_day", the value for a
# specific ``cftime.datetime`` index stands for the resample result
# from the current ``cftime.datetime`` minus ``freq`` to the current
# ``cftime.datetime`` with a right close.
elif self.origin in ["end", "end_day"]:
if isinstance(self.freq, MonthEnd | QuarterEnd | YearEnd) or self.origin in [
"end",
"end_day",
]:
# The backward resample sets ``closed`` to ``'right'`` by default
# since the last value should be considered as the edge point for
# the last bin. When origin in "end" or "end_day", the value for a
# specific ``cftime.datetime`` index stands for the resample result
# from the current ``cftime.datetime`` minus ``freq`` to the current
# ``cftime.datetime`` with a right close.
if closed is None:
self.closed = "right"
else:
Expand Down
14 changes: 6 additions & 8 deletions xarray/groupers.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,25 +701,23 @@ def find_independent_seasons(seasons: Sequence[str]) -> Sequence[SeasonsGroup]:
grouped = defaultdict(list)
codes = defaultdict(list)
seen: set[tuple[int, ...]] = set()
idx = 0
# This is quadratic, but the number of seasons is at most 12
for i, current in enumerate(season_inds):
# Start with a group
if current not in seen:
grouped[idx].append(current)
codes[idx].append(i)
grouped[i].append(current)
codes[i].append(i)
seen.add(current)

# Loop through remaining groups, and look for overlaps
for j, second in enumerate(season_inds[i:]):
if not (set(chain(*grouped[idx])) & set(second)) and second not in seen:
grouped[idx].append(second)
codes[idx].append(j + i)
if not (set(chain(*grouped[i])) & set(second)) and second not in seen:
grouped[i].append(second)
codes[i].append(j + i)
seen.add(second)
if len(seen) == len(seasons):
break
# found all non-overlapping groups for this row, increment and start over
idx += 1
# found all non-overlapping groups for this row start over

grouped_ints = tuple(tuple(idx) for idx in grouped.values() if idx)
return [
Expand Down
2 changes: 1 addition & 1 deletion xarray/plot/facetgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ def map_plot1d(
)

if add_legend:
use_legend_elements = not func.__name__ == "hist"
use_legend_elements = func.__name__ != "hist"
if use_legend_elements:
self.add_legend(
use_legend_elements=use_legend_elements,
Expand Down
7 changes: 4 additions & 3 deletions xarray/plot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,9 +419,10 @@ def _infer_xy_labels(
_assert_valid_xy(darray, x, "x")
_assert_valid_xy(darray, y, "y")

if darray._indexes.get(x, 1) is darray._indexes.get(y, 2):
if isinstance(darray._indexes[x], PandasMultiIndex):
raise ValueError("x and y cannot be levels of the same MultiIndex")
if darray._indexes.get(x, 1) is darray._indexes.get(y, 2) and isinstance(
darray._indexes[x], PandasMultiIndex
):
raise ValueError("x and y cannot be levels of the same MultiIndex")

return x, y

Expand Down
2 changes: 1 addition & 1 deletion xarray/structure/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def merge_collected(
variables = [variable for variable, _ in elements_list]
try:
merged_vars[name] = unique_variable(
name, variables, compat, equals.get(name, None)
name, variables, compat, equals.get(name)
)
except MergeError:
if compat != "minimal":
Expand Down
4 changes: 2 additions & 2 deletions xarray/tests/test_coding.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ def test_coder_roundtrip() -> None:
assert_identical(original, roundtripped)


@pytest.mark.parametrize("dtype", "u1 u2 i1 i2 f2 f4".split())
@pytest.mark.parametrize("dtype2", "f4 f8".split())
@pytest.mark.parametrize("dtype", ["u1", "u2", "i1", "i2", "f2", "f4"])
@pytest.mark.parametrize("dtype2", ["f4", "f8"])
def test_scaling_converts_to_float(dtype: str, dtype2: str) -> None:
dt = np.dtype(dtype2)
original = xr.Variable(
Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_dask.py
Original file line number Diff line number Diff line change
Expand Up @@ -1636,7 +1636,7 @@ def test_normalize_token_with_backend(map_ds):
with create_tmp_file(allow_cleanup_failure=ON_WINDOWS) as tmp_file:
map_ds.to_netcdf(tmp_file)
read = xr.open_dataset(tmp_file)
assert not dask.base.tokenize(map_ds) == dask.base.tokenize(read)
assert dask.base.tokenize(map_ds) != dask.base.tokenize(read)
read.close()


Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3235,7 +3235,7 @@ def test_shuffle_simple() -> None:
da = xr.DataArray(
dims="x",
data=dask.array.from_array([1, 2, 3, 4, 5, 6], chunks=2),
coords={"label": ("x", "a b c a b c".split(" "))},
coords={"label": ("x", ["a", "b", "c", "a", "b", "c"])},
)
actual = da.groupby(label=UniqueGrouper()).shuffle_to_chunks()
expected = da.isel(x=[0, 3, 1, 4, 2, 5])
Expand Down
4 changes: 1 addition & 3 deletions xarray/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,7 @@ def convert_units(obj, to):
elif isinstance(obj, xr.DataArray):
name = obj.name

new_units = (
to.get(name, None) or to.get("data", None) or to.get(None, None) or None
)
new_units = to.get(name) or to.get("data") or to.get(None) or None
data = convert_units(obj.variable, {None: new_units})

coords = {
Expand Down
2 changes: 1 addition & 1 deletion xarray/util/print_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def get_sys_info():
if os.path.isdir(".git") and os.path.isdir("xarray"):
try:
pipe = subprocess.Popen(
'git log --format="%H" -n 1'.split(" "),
("git", "log", '--format="%H"', "-n", "1"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
Expand Down
Loading