Skip to content

Commit 43746b1

Browse files
committed
NF: add utils module for code support functions
Add to_scalar function with tests.
1 parent 3d59146 commit 43746b1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-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

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

0 commit comments

Comments
 (0)