Skip to content

Instantly share code, notes, and snippets.

@jhbuhrman
Last active November 22, 2018 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhbuhrman/b956a2984e10e6e928e9db50cf8995e6 to your computer and use it in GitHub Desktop.
Save jhbuhrman/b956a2984e10e6e928e9db50cf8995e6 to your computer and use it in GitHub Desktop.
Some extra iterable convenience functions
# Copyright 2018 Jan-Hein Bührman
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from typing import Iterable, TypeVar, Iterator, Optional
T = TypeVar('T')
def _ensure_empty(iterator: Iterator[T], exception: Exception, value: T) -> T:
"""Return the passed value if iterable is empty, else raise exception
:param iterator: iterator that is expected to be emtpy
:param exception: the exception (instance already) to raise
:param value: the value to return if passed iterable is emtpy
:return:
"""
try:
next(iterator)
except StopIteration:
# This is the positive scenario, there should be no value(s) (anymore)
return value
raise exception
def one(iterable: Iterable[T]) -> T:
"""Ensures the iterable contains only one element and return it.
Raise ValueError otherwise.
:param iterable: iterable with values
:return: the found value from the list
"""
iterator = iter(iterable)
del iterable
try:
value = next(iterator)
except StopIteration:
raise ValueError("iterable has no item")
return _ensure_empty(
iterator,
ValueError("iterable has more than one value"),
value)
def zero_or_one(iterable: Iterable[T]) -> Optional[T]:
"""Ensures iterable contains either one entry or is empty.
Return the found entry or None. Raise ValueError otherwise.
:param iterable: iterable or sequence with values
:return: the found value from the list or None if empty
"""
iterator = iter(iterable)
del iterable
try:
value = next(iterator)
except StopIteration:
return None
return _ensure_empty(
iterator,
ValueError("iterable has more than one value"),
value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment