Skip to content
Open
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
22 changes: 22 additions & 0 deletions nibabel/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
""" Test for utils module
"""

import numpy as np

from nibabel.utils import to_scalar

from nose.tools import assert_equal, assert_true, assert_false, assert_raises


def test_to_scalar():
for pass_thru in (2, 2.3, 'foo', b'foo', [], (), [2], (2,), object()):
assert_true(to_scalar(pass_thru) is pass_thru)
for arr_contents in (2, 2.3, 'foo', b'foo'):
arr = np.array(arr_contents)
out = to_scalar(arr)
assert_false(to_scalar(arr) is arr)
assert_equal(out, arr_contents)
# Promote to 1 and 2D and check contents
assert_equal(to_scalar(np.atleast_1d(arr)), arr_contents)
assert_equal(to_scalar(np.atleast_2d(arr)), arr_contents)
assert_raises(ValueError, to_scalar, np.array([1, 2]))
21 changes: 21 additions & 0 deletions nibabel/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
""" Code support routines, not otherwise classified
"""


def to_scalar(val):
""" Return scalar representation of `val`

Return scalar value from numpy array, or pass through value if not numpy
array.

Parameters
----------
val : object
numpy array or other object.

Returns
-------
out : object
Result of ``val.item()`` if `val` has an ``item`` method, else `val`.
"""
return val.item() if hasattr(val, 'item') else val