Skip to content

MRG: informative error when trying to slice images #271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions nibabel/spatialimages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
=======================================

Expand Down Expand Up @@ -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]`")
6 changes: 6 additions & 0 deletions nibabel/tests/test_image_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down