Skip to content

Instantly share code, notes, and snippets.

@rtweeks
Created October 20, 2021 04:34
Show Gist options
  • Save rtweeks/26f36f4667fdd40d33852c672971dcad to your computer and use it in GitHub Desktop.
Save rtweeks/26f36f4667fdd40d33852c672971dcad to your computer and use it in GitHub Desktop.
Get a Python iterator that tests as false if empty
# This work is dedicated to the public domain or, in any case where copyright may not be relinquished, offered under an MIT License
def _falsey_on_empty(iterable: Iterable[T]) -> Iterable[T]:
"""Return an iterable that is falsey if empty, but always yields the same elements
:returns:
``()`` if *iterable* is empty, otherwise an iterable over the same
values
Iterable values cannot be generally relied on to return ``False`` when
passed to :func:`bool` if empty. This function converts empty iterators
to the empty :class:`tuple`, which does evaluate as false in a Boolean
context.
"""
remaining_items = iter(iterable)
try:
first = next(remaining_items)
except StopIteration:
return ()
return itertools.chain((first,), remaining_items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment