Skip to content

Variable may contain numpy scalars with numpy>=2.1 #9399

@keewis

Description

@keewis

What is your issue?

I'm not sure if this is a bad thing or not, but while writing tests @TomNicholas and I noticed that starting with numpy=2.1, Variable objects may contain numpy scalars, especially as the result of an aggregation like mean.

This is caused by numpy scalars gaining a __array_namespace__ method, which is then interpreted by as_compatible_data as an actual array.

To fix this, we could change

if not isinstance(data, np.ndarray) and (
hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__")
):
to

if not isinstance(data, (np.numeric, np.ndarray)) and ( 
    hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__") 
):

but not sure if that's worth it.

To reproduce, try this in an environment with numpy>=2.1:

import numpy as np
import xarray as xr

v = xr.Variable((), np.float64(4.1))
repr(v)
# <xarray.Variable ()> Size: 8B
# np.float64(4.1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions