Skip to content

Commit

Permalink
NF: add utils module for code support functions
Browse files Browse the repository at this point in the history
Add to_scalar function with tests.
  • Loading branch information
matthew-brett committed Apr 14, 2017
1 parent 314f0dd commit 6a7887f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
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]))
20 changes: 20 additions & 0 deletions nibabel/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
""" 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

0 comments on commit 6a7887f

Please sign in to comment.