Skip to content

Commit d2b5477

Browse files
committed
-
1 parent 2d336f3 commit d2b5477

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

source_py3/python_toolbox/cute_iter_tools.py

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -315,9 +315,30 @@ def _fill(iterable, fill_value=None, fill_value_maker=None, length=infinity):
315315
yield fill_value_maker()
316316

317317

318+
def get_single_if_any(iterable,
319+
exception_on_multiple=Exception('More than one value '
320+
'not allowed.')):
321+
'''
322+
Get the single item of `iterable`, if any.
318323
319-
320-
321-
322-
323-
324+
If `iterable` has one item, return it. If it's empty, get `None`. If it has
325+
more than one item, raise an exception. (Unless
326+
`exception_on_multiple=None`.)
327+
'''
328+
assert isinstance(exception_on_multiple, Exception) or \
329+
exception_on_multiple is None
330+
iterator = iter(iterable)
331+
try:
332+
first_item = next(iterator)
333+
except StopIteration:
334+
return None
335+
else:
336+
if exception_on_multiple:
337+
try:
338+
second_item = next(iterator)
339+
except StopIteration:
340+
return first_item
341+
else:
342+
raise exception_on_multiple
343+
else: # not exception_on_multiple
344+
return first_item
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Copyright 2009-2013 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
from python_toolbox import cute_testing
5+
6+
from python_toolbox.cute_iter_tools import get_single_if_any
7+
8+
9+
def test_get_single_if_any():
10+
11+
assert get_single_if_any(()) is get_single_if_any([]) is \
12+
get_single_if_any({}) is get_single_if_any(iter({})) is \
13+
get_single_if_any('') is None
14+
15+
assert get_single_if_any(('g',)) == get_single_if_any(['g']) == \
16+
get_single_if_any({'g'}) == get_single_if_any(iter({'g'})) == \
17+
get_single_if_any('g') == 'g'
18+
19+
with cute_testing.RaiseAssertor():
20+
get_single_if_any(('g', 'e', 'e'))
21+
22+
with cute_testing.RaiseAssertor():
23+
get_single_if_any('gee')
24+
25+
assert get_single_if_any('gee', exception_on_multiple=None) == 'g'

0 commit comments

Comments
 (0)