Skip to content

Commit 6a7887f

Browse files
committed
NF: add utils module for code support functions
Add to_scalar function with tests.
1 parent 314f0dd commit 6a7887f

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

nibabel/tests/test_utils.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
""" Test for utils module
2+
"""
3+
4+
import numpy as np
5+
6+
from nibabel.utils import to_scalar
7+
8+
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
9+
10+
11+
def test_to_scalar():
12+
for pass_thru in (2, 2.3, 'foo', b'foo', [], (), [2], (2,), object()):
13+
assert_true(to_scalar(pass_thru) is pass_thru)
14+
for arr_contents in (2, 2.3, 'foo', b'foo'):
15+
arr = np.array(arr_contents)
16+
out = to_scalar(arr)
17+
assert_false(to_scalar(arr) is arr)
18+
assert_equal(out, arr_contents)
19+
# Promote to 1 and 2D and check contents
20+
assert_equal(to_scalar(np.atleast_1d(arr)), arr_contents)
21+
assert_equal(to_scalar(np.atleast_2d(arr)), arr_contents)
22+
assert_raises(ValueError, to_scalar, np.array([1, 2]))

nibabel/utils.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
""" Code support routines, not otherwise classified
2+
"""
3+
4+
def to_scalar(val):
5+
""" Return scalar representation of `val`
6+
7+
Return scalar value from numpy array, or pass through value if not numpy
8+
array.
9+
10+
Parameters
11+
----------
12+
val : object
13+
numpy array or other object.
14+
15+
Returns
16+
-------
17+
out : object
18+
Result of ``val.item()`` if `val` has an ``item`` method, else `val`.
19+
"""
20+
return val.item() if hasattr(val, 'item') else val

0 commit comments

Comments
 (0)