Skip to content

Instantly share code, notes, and snippets.

@AstraLuma
Created November 17, 2016 15:07
Show Gist options
  • Save AstraLuma/9cf4c5bdeb33109816ff97a70c242da1 to your computer and use it in GitHub Desktop.
Save AstraLuma/9cf4c5bdeb33109816ff97a70c242da1 to your computer and use it in GitHub Desktop.
class ErrorCounter(collections.Counter):
"""
Repeatable context manager. Counts the types of errors when exiting.
Note that expected exceptions are surpressed.
Generally, replaces constructs like:
for egg in spam():
try:
egg.do_the_thing()
except A:
aerrs += 1
except B:
berrs += 1
with things like:
ec = ErrorCounter(A, B)
for egg in spam():
with ec:
egg.do_the_thing()
aerrs = ec.count(A)
berrs = ec.count(B)
"""
def __init__(self, *expectedtypes):
"""
Takes expected types, or assumes all are expected if None are given.
"""
super().__init__()
if expectedtypes:
self._types = expectedtypes
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self[exception_type] += 1
if self._types is None:
return True
elif exception_type is None:
return True
else:
return exception_type in self._types
def successes(self):
"""
Return the number of successful results.
"""
return self[None]
def count(self, *types):
"""
Count the errors of the given types, or all of them if none are given.
"""
if len(types):
return sum(v for k, v in self.items() if k in types)
else:
return sum(v for k, v in self.items() if k is not None)
def count_but(self, *types):
"""
Count the errors of except the given types.
"""
types = tuple(types) + (None,)
return sum(v for k, v in self.items() if k not in types)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment