Skip to content
Snippets Groups Projects
Commit 9ec569be authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

added `exhaust` to `is_empty`

parent 5dbdf72e
No related branches found
No related tags found
No related merge requests found
......@@ -3,3 +3,4 @@
* add `SparseMatrix.min` and `SparseMatrix.max`
* `SparseMatrix.getitem` will raise IndexError on invalid coordinates
* added `index_of` and `index_of_max`
* added `exhaust` to `is_empty`
__version__ = '2.11.30_a4'
__version__ = '2.11.30_a5'
......@@ -415,19 +415,27 @@ class IteratorListAdapter:
return len(self.list)
def is_empty(iterable: IteratorOrIterable) -> bool:
@silence_excs(StopIteration, returns=True)
def is_empty(iterable: IteratorOrIterable, exhaust: bool = True) -> bool:
"""
Checks whether an iterator is empty.
This will exhaust the iterator.
This will exhaust the iterator if exhaust is left at default, or True
:param iterable: iterator to check
:param exhaust: if set to False, at most a single element will be consumed
from the iterator
:return: whether the iterator is empty
"""
i = 0
for elem in iterable:
i += 1
return i == 0
iterator = iter(iterable)
if exhaust:
i = 0
for _ in iterator:
i += 1
return i == 0
else:
next(iterator)
return False
def map_list(fun: tp.Callable, iterable: IteratorOrIterable) -> tp.List:
......
......@@ -3,11 +3,19 @@ import unittest
from satella.coding import SelfClosingGenerator, hint_with_length, chain
from satella.coding.sequences import smart_enumerate, ConstruableIterator, walk, \
IteratorListAdapter
IteratorListAdapter, is_empty
class TestIterators(unittest.TestCase):
def test_is_empty_not_exhaust(self):
def generator():
yield 1
raise ValueError()
self.assertFalse(is_empty(generator(), exhaust=False))
self.assertTrue(is_empty([], exhaust=False))
def test_generator_list_adapter(self):
gla = IteratorListAdapter(range(10))
self.assertEqual(next(gla), 0)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment