Skip to content

DeprecationWarning for assigning to numpy.ndarray.shape #1468

@keewis

Description

@keewis

(caught by xarray's upstream-dev CI)

numpy is deprecating assignment to the shape property of numpy.ndarray instances in numpy>=2.5.0, which netCDF4 appears to be doing. To reproduce:

import netCDF4
import numpy as np
import warnings

warnings.filterwarnings("error")  # raise on all warnings

with netCDF4.Dataset("test.nc", mode="w") as ds:
    x = ds.createDimension("x", 3)
    y = ds.createDimension("y", 4)
    var = ds.createVariable("a", "f4", ("y", "x"), fill_value=np.nan)
    var.set_always_mask(False)
    var.set_auto_mask(False)
    
    new_data = np.array([[ 1.76405235,  0.40015721,  0.97873798],
       [ 2.2408932 ,         np.nan, -0.97727788],
       [ 0.95008842, -0.15135721, -0.10321885],
       [ 0.4105985 ,  0.14404357,  1.45427351]], dtype="f4")
    var[...] = new_data

(not sure if both set_always_mask and set_auto_mask is necessary, but the warning is raised in the assignment of the data)

Result:

Traceback (most recent call last):
  File "<python-input-6>", line 18, in <module>
    var[...] = new_data
    ~~~^^^^^
  File "src/netCDF4/_netCDF4.pyx", line 5633, in netCDF4._netCDF4.Variable.__setitem__
DeprecationWarning: Setting the shape on a NumPy array has been deprecated in NumPy 2.5.
As an alternative, you can create a new view using np.reshape (with copy=False if needed).

Edit: the version of netCDF4 is 1.7.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions