Subclasses cannot preserve their types during some binary ops and ufuncs combining DataArray and Dataset

Abierto
#11,829 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@AtharvRG ya está trabajando en esto.

Desde el 31/10/2026.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
38/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
numpy, python
Área
backend

Línea de trabajo

Read xr.Dataset._binary_op and SupportsArithmetic.__array_ufunc__, then locate the existing tests for binary operations and ufuncs involving DataArray and Dataset. The proposed hooks and their exact API require maintainer agreement, so confirm the intended subclass protocol before editing. Done means the three listed combinations return the specialized subclass type while existing non-subclass behavior remains covered by tests.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

needs triage
What is your issue?

From uxarray downstream (UXARRAY/uxarray#1802). While xarray currently discourages subclassing in general, it does also point out uxarray in particular as an example where subclassing is used. In the context of uxarray, it is desirable and intuitive for binary operations and ufuncs involving a uxarray object and an xarray object to return a result which uses the more-specialized uxarray type.

The heart of the issue here is that xarray supports binary operations and binary ufuncs with one input being a Dataset and the other being a DataArray, but currently checks whether it should handle operations directly by checking isinstance(obj, xr.DataArray) or isinstance(obj, xr.Dataset) (which give True even for subclasses). When True, xarray fully handles the operations in a few cases, before subclasses ever get a chance to override anything. These cases are:

  1. xr.Dataset * CustomDataArray, where * can be any binary operation (e.g. multiplication, addition, subtraction)
  2. ufunc(xr.Dataset, CustomDataArray), where ufunc can be any numpy binary ufunc (e.g. np.minimum, np.divmod)
  3. ufunc(xr.DataArray, CustomDataset), where ufunc can be any numpy binary ufunc (e.g. np.minimum, np.divmod)

All other combinations (such as xr.Dataset * CustomDataset, ufunc(xr.DataArray, CustomDataArray), and even xr.DataArray * CustomDataset) can be overridden by the subclass directly, returning the CustomDataset or CustomDataArray type one might hope for (UXARRAY/uxarray#1767 handled this for uxarray). However, these three remaining cases cannot fixed directly in the subclass, because:

  • For (1), the operation goes directly to xr.Dataset's methods, and when xr.Dataset sees that the second term is an instance of xr.DataArray it decides to handle everything, without giving the second term a chance to alter the behavior in any way.
  • For (2) and (3), when numpy applies the ufunc here it sees that the first term is not a subclass of the second term (or vice versa), so it starts checking for any __array_ufunc__ methods on the inputs, in order. This leads to applying the xarray object's __array_ufunc__, which similarly decides to handle everything after seeing that the second term is an instance of an xarray object (xr.DataArray in (2); xr.Dataset in (3)), also without giving the second term a chance to alter the behavior in any way.

One possible solution would be to introduce hooks or flags which do nothing in xarray, but which subclasses could override to regain control. For (1), I believe there would just need to be a hook inside xr.Dataset._binary_op, inside the if isinstance(other, DataArray | Dataset): block. It could probably be something as simple as if getattr(other, "_subclass_overrides_binary_op", False): return NotImplemented. For (2) and (3), I believe there would just need to be a hook inside SupportsArithmetic.__array_ufunc__, something like for x in inputs: if isinstance(x, SupportsArithmetic) and getattr(x, "_subclass_overrides_array_ufunc", False): return NotImplemented.

I would be very interested to open a PR to solve this issue, if xarray maintainers agree that something like this would sound reasonable. Also happy to take any suggestions on this topic, or clarify further if anything isn't clear!

Related: #3980

Lenguaje dominante
Python
Estrellas
4.2k
Forks
1.5k
Merge medio
2 d 21 h
PR fusionados (30 d)
74

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de pydata/xarray

Todos los issues de pydata/xarray

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.