Skip to content

Commit 0bd70c0

Browse files
Fix indexing syntax not valid for Python<3.11. (#185)
* Fix indexing not working with Python 3.10. * Changenote. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 5ed6291 commit 0bd70c0

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Made indexing work with Python v3.10.

lib/ncdata/_core.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -500,8 +500,12 @@ def slicer(self, *dim_names):
500500

501501
return Slicer(self, *dim_names)
502502

503-
def __getitem__(self, keys): # noqa: D105
504-
return self.slicer()[*keys]
503+
def __getitem__(self, indices): # noqa: D105
504+
# N.B. Python [,,] syntax ensures there is only ever one argument,
505+
# either a single key or a tuple :
506+
# : [x] --> keys == x
507+
# : [x, y, ...] --> keys == (x, y, ...)
508+
return self.slicer().__getitem__(indices)
505509

506510
# Define equality in terms of dataset comparison utility
507511
def __eq__(self, other): # noqa: D105

tests/unit/core/test_NcData.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
There is almost no behaviour, but we can test some constructor usages.
44
"""
55

6+
import pytest
67
from ncdata import NcData, NcDimension, NcVariable
78

89

@@ -99,17 +100,28 @@ def test(self, mocker):
99100

100101
class Test_NcVariable_getitem:
101102
# check that data[*keys] calls data.slicer[*keys]
102-
def test(self, mocker):
103+
@pytest.mark.parametrize(
104+
"multiple_indices", [False, True], ids=["oneIndex", "multiIndex"]
105+
)
106+
def test(self, mocker, multiple_indices):
103107
from ncdata.utils import Slicer
104108

105109
ncdata1 = NcData()
106110

107-
dim_keys = (1, 2, 3) # N.B. not actually acceptable for a real usage
108111
mock_slicer = mocker.MagicMock(spec=Slicer)
109112
called = mocker.patch(
110113
"ncdata._core.NcData.slicer", return_value=mock_slicer
111114
)
112-
result = ncdata1[*dim_keys]
115+
if multiple_indices:
116+
# Index with multiple keys, which should be passed as a tuple
117+
# Slightly awkward code, because the "[*keys]" syntax is only valid from
118+
# Python >=3.11
119+
result = ncdata1[1, 2, 3]
120+
dim_keys = (1, 2, 3)
121+
else:
122+
# Index with a single key: should be passed as-is
123+
dim_keys = slice(0, 3)
124+
result = ncdata1[dim_keys]
113125

114126
assert called.call_args_list == [mocker.call()]
115127
assert mock_slicer.__getitem__.call_args_list == [

0 commit comments

Comments
 (0)