Commits

Anonymous committed ae54e69

Added iter_.one

Comments (0)

Files changed (2)

 3.3
 ~~~
 
-* Added prorating calculator and console script prorate-calc.
+* Added prorating calculator and console script calc-prorate.
 * Added iter_.peek
 * Renamed QuickTimer to Stopwatch - modified to PEP8 specs
 * Adding jaraco.filesystem.DirectoryStack
+* Added iter_.one and iter_.first
 
 3.2
 ~~~

jaraco/util/iter_.py

 """jaraco.iter_
 	Tools for working with iterables.  Complements itertools.
 	
-Copyright © 2008-2009 Jason R. Coombs
+Copyright © 2008-2010 Jason R. Coombs
 """
 
 __author__ = 'Jason R. Coombs <jaraco@jaraco.com>'
 	peeker, original = itertools.tee(iterable)
 	return next(peeker), original
 
+def first(item):
+	iterable = iter(item)
+	return next(iterable)
+
+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: item contained more than one value
+	"""
+	iterable = iter(item)
+	result = next(iterable)
+	if tuple(itertools.islice(iterable, 1)):
+		raise ValueError("item contained more than one value")
+	return result