From c44ab31492a3b386e566a9b7374c7a0f6da19659 Mon Sep 17 00:00:00 2001 From: Matthew Brett Date: Fri, 14 Nov 2014 15:18:20 -0800 Subject: [PATCH] NF: informative error when trying to slice images From suggestion by Eric L. --- nibabel/spatialimages.py | 10 ++++++++++ nibabel/tests/test_image_api.py | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/nibabel/spatialimages.py b/nibabel/spatialimages.py index 34b28c5b18..73104e4ca5 100644 --- a/nibabel/spatialimages.py +++ b/nibabel/spatialimages.py @@ -43,6 +43,9 @@ * instance_to_filename(img, fname) - save ``img`` instance to filename ``fname``. +You cannot slice an image, and trying to slice an image generates an +informative TypeError. + There are several ways of writing data. ======================================= @@ -734,3 +737,10 @@ def from_image(klass, img): img.affine, klass.header_class.from_header(img.header), extra=img.extra.copy()) + + def __getitem__(self): + ''' No slicing or dictionary interface for images + ''' + raise TypeError("Cannot slice image objects; consider slicing image " + "array data with `img.dataobj[slice]` or " + "`img.get_data()[slice]`") diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index 0dd615425f..1565d165a2 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -16,6 +16,7 @@ * ``img.uncache()`` (``img.get_data()`` is allowed to cache the result of the array creation. If it does, this call empties that cache. Implement this as a no-op if ``get_data()`` does not cache. +* ``img[something]`` generates an informative TypeError """ from __future__ import division, print_function, absolute_import @@ -234,6 +235,11 @@ def validate_filenames(self, imaker, params): assert_almost_equal(img.get_data(), rt_img.get_data()) del rt_img # to allow windows to delete the directory + def validate_no_slicing(self, imaker, params): + img = imaker() + assert_raises(TypeError, img.__getitem__, 'string') + assert_raises(TypeError, img.__getitem__, slice(None)) + class LoadImageAPI(GenericImageAPI): # Callable returning an image from a filename