Commits

Jason R. Coombs committed 653173a

Adding itertools.suppress_exceptions

  • Participants
  • Parent commits 827d61d
  • Tags 6.2

Comments (0)

Files changed (2)

 Changes
 -------
 
-6.2dev
+6.2
 ~~~
 
 * Added IntervalGovernor to `timing` module. Allows one to decorate a
   function, causing that function to only be called once per interval, despite
   the number of calls attempted.
+* Added `itertools.suppress_exceptions`. Use it to iterate over callables,
+  suppressing exceptions.
 
 6.1
 ~~~

File jaraco/util/itertools.py

 	if isinstance(item, basestring) or not hasattr(item, '__iter__'):
 		item = item,
 	return item
+
+def suppress_exceptions(callables, *exceptions):
+	"""
+	Call each callable in callables, suppressing any exceptions supplied. If
+	no exception classes are supplied, all Exceptions will be suppressed.
+
+	>>> import functools
+	>>> c1 = functools.partial(int, 'a')
+	>>> c2 = functools.partial(int, '10')
+	>>> list(suppress_exceptions((c1, c2)))
+	[10]
+	>>> list(suppress_exceptions((c1, c2), KeyError))
+	Traceback (most recent call last):
+	...
+	ValueError: invalid literal for int() with base 10: 'a'
+	"""
+	if not exceptions:
+		exceptions = Exception,
+	for callable in callables:
+		try:
+			yield callable()
+		except exceptions:
+			pass