Skip to content

Commit fe72446

Browse files
Merge pull request #533 from arokem/getitem_inputs
MRG: Improve error handling for `img.__getitem__` Show helpful error when user tries to index the image object.
2 parents fd00d7d + ce1d07f commit fe72446

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

nibabel/spatialimages.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ def from_image(klass, img):
460460
klass.header_class.from_header(img.header),
461461
extra=img.extra.copy())
462462

463-
def __getitem__(self):
463+
def __getitem__(self, idx):
464464
''' No slicing or dictionary interface for images
465465
'''
466466
raise TypeError("Cannot slice image objects; consider slicing image "

nibabel/tests/test_spatialimages.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,14 @@ def test_get_data(self):
312312
in_data_template = np.arange(24, dtype=np.int16).reshape((2, 3, 4))
313313
in_data = in_data_template.copy()
314314
img = img_klass(in_data, None)
315+
# Can't slice into the image object:
316+
with assert_raises(TypeError) as exception_manager:
317+
img[0, 0, 0]
318+
# Make sure the right message gets raised:
319+
assert_equal(str(exception_manager.exception),
320+
("Cannot slice image objects; consider slicing image "
321+
"array data with `img.dataobj[slice]` or "
322+
"`img.get_data()[slice]`"))
315323
assert_true(in_data is img.dataobj)
316324
out_data = img.get_data()
317325
assert_true(in_data is out_data)

0 commit comments

Comments
 (0)