Skip to content

Commit 228ecd3

Browse files
committed
-
1 parent d2b5477 commit 228ecd3

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

source_py2/python_toolbox/cute_iter_tools.py

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

322322

323+
def get_single_if_any(iterable,
324+
exception_on_multiple=Exception('More than one value '
325+
'not allowed.')):
326+
'''
327+
Get the single item of `iterable`, if any.
323328
324-
325-
326-
327-
328-
329+
If `iterable` has one item, return it. If it's empty, get `None`. If it has
330+
more than one item, raise an exception. (Unless
331+
`exception_on_multiple=None`.)
332+
'''
333+
assert isinstance(exception_on_multiple, Exception) or \
334+
exception_on_multiple is None
335+
iterator = iter(iterable)
336+
try:
337+
first_item = next(iterator)
338+
except StopIteration:
339+
return None
340+
else:
341+
if exception_on_multiple:
342+
try:
343+
second_item = next(iterator)
344+
except StopIteration:
345+
return first_item
346+
else:
347+
raise exception_on_multiple
348+
else: # not exception_on_multiple
349+
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)