Registry Mirror
Skip to content

Conversation

@andrew-s28

@andrew-s28 andrew-s28 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

The methods for the documented reduction operations on Dataset.coarsen() and DataArray.coarsen() were dynamically generated via injected methods that relied on code in several different modules. The dynamic generation of these methods also meant that type errors were raised when trying to access reduction methods, e.g., the following code example.

Minimal working example
import numpy as np
import xarray as xr

rng = np.random.default_rng(42)
data = rng.random((10, 10))

ds = xr.Dataset(
    {
        "z": (("x", "y"), data)
    },
    coords={
        "x": np.arange(10),
        "y": np.arange(10)
    },
)

# raises Object of type `DatasetCoarsen` has no attribute `mean` ty[unresolved-attribute]
ds_coarsen = ds.coarsen(x=2).mean() 

This PR moves all the logic for Coarsen into xarray.computation.rolling and attempts to mirror the implementation of xarray.computation.rolling.Rolling. It should result in no functional changes as far as I can tell and should make future maintenance slightly easier (not having to track the injection across files).

Checklist

PS: I think the xarray.computation.rolling module might be due for a refactoring and don't seem to have been touched a lot in recent years. There's also #8059 related to this module, which I didn't address here to keep the scope limited. Happy to discuss a larger refactoring effort if there's any interest 😄

@andrew-s28 andrew-s28 changed the title Fixes type error for Coarsen reduction methods Fix type error for Coarsen reduction methods Sep 1, 2026
@dcherian

dcherian commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

That's a nice improvement! Can you fix the mypy errors please?

We ccould explore move these to https://github.com/pydata/xarray/blob/main/xarray/util/generate_aggregations.py but I think part of the issue is how some of these aggregations are written in terms of others.

@andrew-s28

Copy link
Copy Markdown
Contributor Author

@dcherian type checking seems to be passing now.

Thanks for your thoughts on the module overall, too.

I think it would be ideal to get these reductions in terms of the aggregations in generate_aggregations. There's just the question of how much API change (in terms of args, kwargs, etc.) is acceptable, since the APIs for the coarsen and rolling methods seem somewhat unique. Rolling is also doing some stuff that is not present in coarsen or aggregations as far as I can tell with numbagg and bottleneck optimizations.

One potentially "lower hanging fruit" option would be to just better align the implementations of rolling and coarsen within the rolling.py module, which would probably make any later refactoring easier too. I focused this PR more on addressing the type error while reproducing the behavior of coarsen 1:1 with it's previous dynamic method generation; a follow-up PR could do more to reduce duplication and align the module, but would necessarily involve more changes, so wanted to get xarray dev input before I tried putting anything bigger together.

@dcherian

dcherian commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

yes no worries, i remember looking into it and giving up hehe.

thank you, i will merge now

@dcherian
dcherian merged commit 864cb2d into pydata:main Sep 4, 2026
42 checks passed
@LOCEANlloydizard

Copy link
Copy Markdown

Hi @andrew-s28, just commenting here before opening an issue: we hit a problem with xarray 2026.9.0 and I wanted to confirm whether this is expected behavior. For example:

import xarray as xr

da = xr.DataArray(
    [1.0, float("nan"), 3.0, 4.0],
    dims="x",
)

da.coarsen(x=2, boundary="pad").mean(skipna=True)

raises:

TypeError: DataArrayCoarsen._reduce_method() got an unexpected keyword argument 'skipna'

We worked around this in echostack-org/echopype#1796 by removing the explicit skipna=True but from the discussion here, I understood that the refactor was intended to preserve the existing Coarsen behavior? Then should skipna still be accepted for these reductions? cheers!

@andrew-s28

Copy link
Copy Markdown
Contributor Author

Hey @LOCEANlloydizard thanks for catching this! I could have sworn I checked all such possibilities, but clearly not. It seems to be a result of duplicated **kwargs in the creation of the reduction method function.

You may already know this, but for completeness sake: this **kwargs is eventually passed to the underlying reduction function through the _create_nan_agg_method function. The **kwargs that is passed from coarsen includes only skipna, though it is confusingly internally set to None, which still results in the desired behavior). This is all part of the motivation for a larger clean up of this code 😄

Feel free to open an issue! I will add a PR ASAP addressing this that also includes regression tests against this (which clearly aren't included yet). Sorry for the mistake!

@andrew-s28

Copy link
Copy Markdown
Contributor Author

#11686 has been submitted to address this

@LOCEANlloydizard

Copy link
Copy Markdown

hey @andrew-s28 sorry i was AFK yesterday, thx for opening the PR and looking into this! I figured it would still be pretty fresh for you to look into haha! and I know there’s always something that slips through, no matter how many possibilities you check.. 😄 thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Type checking fails for DataArrayCoarsen methods

3 participants