Skip to content

Commit e8ea132

Browse files
committed
Merge pull request #271 from matthew-brett/error-on-slice
MRG: informative error when trying to slice images From suggestion by Eric L.
2 parents 5c5682e + c44ab31 commit e8ea132

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

nibabel/spatialimages.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@
4343
* instance_to_filename(img, fname) - save ``img`` instance to
4444
filename ``fname``.
4545
46+
You cannot slice an image, and trying to slice an image generates an
47+
informative TypeError.
48+
4649
There are several ways of writing data.
4750
=======================================
4851
@@ -734,3 +737,10 @@ def from_image(klass, img):
734737
img.affine,
735738
klass.header_class.from_header(img.header),
736739
extra=img.extra.copy())
740+
741+
def __getitem__(self):
742+
''' No slicing or dictionary interface for images
743+
'''
744+
raise TypeError("Cannot slice image objects; consider slicing image "
745+
"array data with `img.dataobj[slice]` or "
746+
"`img.get_data()[slice]`")

nibabel/tests/test_image_api.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* ``img.uncache()`` (``img.get_data()`` is allowed to cache the result of the
1717
array creation. If it does, this call empties that cache. Implement this
1818
as a no-op if ``get_data()`` does not cache.
19+
* ``img[something]`` generates an informative TypeError
1920
"""
2021
from __future__ import division, print_function, absolute_import
2122

@@ -234,6 +235,11 @@ def validate_filenames(self, imaker, params):
234235
assert_almost_equal(img.get_data(), rt_img.get_data())
235236
del rt_img # to allow windows to delete the directory
236237

238+
def validate_no_slicing(self, imaker, params):
239+
img = imaker()
240+
assert_raises(TypeError, img.__getitem__, 'string')
241+
assert_raises(TypeError, img.__getitem__, slice(None))
242+
237243

238244
class LoadImageAPI(GenericImageAPI):
239245
# Callable returning an image from a filename

0 commit comments

Comments
 (0)