Skip to content

Fix type error for Coarsen reduction methods - #11556

Open
andrew-s28 wants to merge 3 commits into
pydata:mainfrom
andrew-s28:coarsen-type-support
Open

Fix type error for Coarsen reduction methods#11556
andrew-s28 wants to merge 3 commits into
pydata:mainfrom
andrew-s28:coarsen-type-support

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.

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

2 participants