From 32ce7b171853a35dcbe4384b97124fffc8bb0d50 Mon Sep 17 00:00:00 2001 From: Zakhar Pashkin <112114097+zack-dev-cm@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:24:05 +0400 Subject: [PATCH] Restore IndexError for oversized empty slice writes Signed-off-by: Zakhar Pashkin <112114097+zack-dev-cm@users.noreply.github.com> --- src/netCDF4/utils.py | 15 +++++++++--- test/test_empty_indexing.py | 48 +++++++++++++++++++++++++++++++++++-- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/src/netCDF4/utils.py b/src/netCDF4/utils.py index bd9c51ff4..600e00581 100644 --- a/src/netCDF4/utils.py +++ b/src/netCDF4/utils.py @@ -213,6 +213,7 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\ # replace boolean arrays with sequences of integers. newElem = [] + has_explicit_slice = False IndexErrorMsg=\ "only integers, slices (`:`), ellipsis (`...`), and 1-d integer or boolean arrays are valid indices" i=0 @@ -226,7 +227,8 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\ except: raise IndexError(IndexErrorMsg) # plain integers, slices and ellipsis need no numpy conversion. - simple = type(e) is int or type(e) is slice or e is Ellipsis + index_type = type(e) + simple = index_type is int or index_type is slice or e is Ellipsis if not simple: ea = np.asarray(e) # Raise error if multidimensional indexing is used. @@ -243,11 +245,13 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\ else: unlim = False # integer scalar - if type(e) is int: + if index_type is int: newElem.append(e) # slice or ellipsis object elif simple: - if not use_get_vars and type(e) == slice and e.step not in [None,-1,1] and\ + # Preserve slice intent across both strided and empty-index conversion. + has_explicit_slice = has_explicit_slice or index_type is slice + if not use_get_vars and index_type is slice and e.step not in [None,-1,1] and\ dimensions is not None and grp is not None: # convert strided slice to integer sequence if possible # (this will avoid nc_get_vars, which is slow - issue #680). @@ -502,6 +506,11 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\ indices_[:] = indices indices = indices_.reshape(compact) + if (empty and put and has_explicit_slice and dimensions is not None and len(dimensions) == 1 + and datashape is not None and len(datashape) == 1 and datashape[0] > 1): + # Report the same size mismatch as _put for an oversized slice write. + raise IndexError("size of data array does not conform to slice") + if empty and not put: # Empty reads bypass native bounds checks, including those for vlens. for i, e in enumerate(elem): diff --git a/test/test_empty_indexing.py b/test/test_empty_indexing.py index d6794af5c..38adbf873 100644 --- a/test/test_empty_indexing.py +++ b/test/test_empty_indexing.py @@ -2,6 +2,7 @@ import os import tempfile import unittest +from collections import UserList from typing import Any import numpy as np @@ -261,13 +262,56 @@ def test_one_dimensional_empty_broadcast(self): ds.createDimension('x', 3) variable = ds.createVariable('data', 'i4', ('x',)) variable[:] = [10, 20, 30] - for empty in (EMPTY, slice(0), np.zeros(3, dtype=bool)): + cases = ( + (EMPTY, ValueError), + (slice(0), IndexError), + (np.zeros(3, dtype=bool), ValueError), + ) + for empty, error in cases: with self.subTest(empty=repr(empty)): variable[empty] = np.array([123]) assert_array_equal(variable[:], [10, 20, 30]) - with self.assertRaises((ValueError, IndexError)): + with self.assertRaises(error): variable[empty] = np.array([123, 456]) + def test_oversized_empty_slice_write(self): + path = os.path.join(self.directory.name, 'slice-write.nc') + cases = ( + (None, slice(-3, None)), + (None, (Ellipsis, slice(-2, -2))), + (None, [slice(-3, None)]), + (2, slice(1, 1)), + (2, UserList([slice(1, 1)])), + ) + for length, key in cases: + with self.subTest(length=length, key=key): + with Dataset(path, 'w') as ds: + ds.createDimension('time', length) + variable = ds.createVariable('sensor', 'i4', ('time',)) + variable[:] = [0, 1] + with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'): + variable[key] = [9, 8, 7] + variable[:0] = [9] + self.assertEqual(len(ds.dimensions['time']), 2) + self.assertEqual(variable.shape, (2,)) + assert_array_equal(variable[:], [0, 1]) + + def test_oversized_empty_strided_slice_write(self): + path = os.path.join(self.directory.name, 'strided-write.nc') + for use_get_vars in (False, True): + with self.subTest(use_get_vars=use_get_vars): + with Dataset(path, 'w') as ds: + ds.createDimension('time', 2) + variable = ds.createVariable('sensor', 'i4', ('time',)) + variable[:] = [0, 1] + variable.use_nc_get_vars(use_get_vars) + with self.assertRaisesRegex(IndexError, 'size of data array does not conform to slice'): + variable[4:5:2] = [9, 8, 7] + variable[4:5:2] = [9] + self.assertEqual(len(ds.dimensions['time']), 2) + self.assertEqual(variable.shape, (2,)) + assert_array_equal(variable[:], [0, 1]) + def test_empty_encoded_characters(self): raw = np.array(['alpha', 'bravo', 'delta', 'gamma'], dtype='S5').view('S1').reshape(4, 5) paths = []