1. Jason R. Coombs
  2. jaraco.util

Commits

Jason R. Coombs  committed 423ba21

Restore itertools.one

  • Participants
  • Parent commits c26afc9
  • Branches default
  • Tags 10.0.2

Comments (0)

Files changed (2)

File CHANGES.txt

View file
 Changes
 -------
 
+10.0.2
+~~~~~~
+
+* Restore ``itertools.one``, unintentionally removed in 10.0.
+
+10.0.1
+~~~~~~
+
+* Restore Python 2 compatibility.
+
 10.0
 ~~~~
 

File jaraco/util/itertools.py

View file
 	except NameError:
 		raise ValueError("Iterable contains no items")
 
+def one(item):
+	"""
+	Return the first element from the iterable, but raise an exception
+	if elements remain in the iterable after the first.
+
+	>>> one(['val'])
+	'val'
+
+	>>> one(['val', 'other'])
+	Traceback (most recent call last):
+	...
+	ValueError: too many values to unpack (expected 1)
+
+	>>> one([])
+	Traceback (most recent call last):
+	...
+	ValueError: need more than 0 values to unpack
+
+	>>> numbers = itertools.count()
+	>>> one(numbers)
+	Traceback (most recent call last):
+	...
+	ValueError: too many values to unpack (expected 1)
+	>>> next(numbers)
+	2
+	"""
+	result, = item
+	return result
+
 def nwise(iter, n):
 	"""
 	Like pairwise, except returns n-tuples of adjacent items.