Skip to content

Commit d0b2c29

Browse files
committed
RF: created peek_next util function
1 parent 8a41145 commit d0b2c29

File tree

3 files changed

+25
-6
lines changed

3 files changed

+25
-6
lines changed

nibabel/streamlines/tck.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from .tractogram_file import HeaderError, DataError
2121
from .tractogram import TractogramItem, Tractogram, LazyTractogram
2222
from .header import Field
23+
from .utils import peek_next
2324

2425
MEGABYTE = 1024 * 1024
2526

@@ -201,9 +202,7 @@ def save(self, fileobj):
201202
# Use the first element to check
202203
# 1) the tractogram is not empty;
203204
# 2) quantity of information saved along each streamline.
204-
first_item = next(tractogram)
205-
# Put back the first element at its place.
206-
tractogram = itertools.chain([first_item], tractogram)
205+
first_item, tractogram = peek_next(tractogram)
207206
except StopIteration:
208207
# Empty tractogram
209208
header[Field.NB_STREAMLINES] = 0

nibabel/streamlines/trk.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from .tractogram_file import DataError, HeaderError, HeaderWarning
2323
from .tractogram import TractogramItem, Tractogram, LazyTractogram
2424
from .header import Field
25+
from .utils import peek_next
2526

2627

2728
MAX_NB_NAMED_SCALARS_PER_POINT = 10
@@ -435,9 +436,7 @@ def save(self, fileobj):
435436
# Use the first element to check
436437
# 1) the tractogram is not empty;
437438
# 2) quantity of information saved along each streamline.
438-
first_item = next(tractogram)
439-
# Put back the first element at its place.
440-
tractogram = itertools.chain([first_item], tractogram)
439+
first_item, tractogram = peek_next(tractogram)
441440
except StopIteration:
442441
# Empty tractogram
443442
header[Field.NB_STREAMLINES] = 0

nibabel/streamlines/utils.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import itertools
2+
13
import nibabel
24

35

@@ -29,3 +31,22 @@ def get_affine_from_reference(ref):
2931

3032
# Assume `ref` is the name of a neuroimaging file.
3133
return nibabel.load(ref).affine
34+
35+
36+
def peek_next(iterable):
37+
""" Peek next element of iterable.
38+
39+
Parameters
40+
----------
41+
iterable
42+
Iterable to peek the next element from.
43+
44+
Returns
45+
-------
46+
next_item
47+
Element peeked from `iterable`.
48+
new_iterable
49+
Iterable behaving like if the original `iterable` was untouched.
50+
"""
51+
next_item = next(iterable)
52+
return next_item, itertools.chain([next_item], iterable)

0 commit comments

Comments
 (0)