Skip to content

Commit ec4567f

Browse files
Merge pull request #485 from matthew-brett/more-dtypes-for-fileslice
MRG: allow dtype specifiers as fileslice input Make input to fileslice function more general.
2 parents c5473f8 + f5e1e1e commit ec4567f

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

nibabel/fileslice.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -719,17 +719,19 @@ def fileslice(fileobj, sliceobj, shape, dtype, offset=0, order='C',
719719
Parameters
720720
----------
721721
fileobj : file-like object
722-
binary file-like object. Implements ``read`` and ``seek``
722+
file-like object, opened for reading in binary mode. Implements
723+
``read`` and ``seek``.
723724
sliceobj : object
724-
something that can be used to slice an array as in ``arr[sliceobj]``
725+
something that can be used to slice an array as in ``arr[sliceobj]``.
725726
shape : sequence
726-
shape of full array inside `fileobj`
727-
dtype : dtype object
728-
dtype of array inside `fileobj`
727+
shape of full array inside `fileobj`.
728+
dtype : dtype specifier
729+
dtype of array inside `fileobj`, or input to ``numpy.dtype`` to specify
730+
array dtype.
729731
offset : int, optional
730732
offset of array data within `fileobj`
731733
order : {'C', 'F'}, optional
732-
memory layout of array in `fileobj`
734+
memory layout of array in `fileobj`.
733735
heuristic : callable, optional
734736
function taking slice object, axis length, stride length as arguments,
735737
returning one of 'full', 'contiguous', None. See
@@ -743,7 +745,8 @@ def fileslice(fileobj, sliceobj, shape, dtype, offset=0, order='C',
743745
"""
744746
if is_fancy(sliceobj):
745747
raise ValueError("Cannot handle fancy indexing")
746-
itemsize = dtype.itemsize
748+
dtype = np.dtype(dtype)
749+
itemsize = int(dtype.itemsize)
747750
segments, sliced_shape, post_slicers = calc_slicedefs(
748751
sliceobj, shape, itemsize, offset, order)
749752
n_bytes = reduce(operator.mul, sliced_shape, 1) * itemsize

nibabel/tests/test_fileslice.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,16 @@ def test_fileslice():
740740
_check_slicer(sliceobj, arr, fobj, offset, order)
741741

742742

743+
def test_fileslice_dtype():
744+
# Test that any valid dtype specifier works for fileslice
745+
sliceobj = (slice(None), slice(2))
746+
for dt in (np.dtype('int32'), np.int32, 'i4', 'int32', '>i4', '<i4'):
747+
arr = np.arange(24, dtype=dt).reshape((2, 3, 4))
748+
fobj = BytesIO(arr.tostring())
749+
new_slice = fileslice(fobj, sliceobj, arr.shape, dt)
750+
assert_array_equal(arr[sliceobj], new_slice)
751+
752+
743753
def test_fileslice_errors():
744754
# Test fileslice causes error on fancy indexing
745755
arr = np.arange(24).reshape((2, 3, 4))

0 commit comments

Comments
 (0)