Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Last active March 12, 2026 04:21
Show Gist options
  • Select an option

  • Save pythonhacker/333d5abb369e243885a2dab25f47912c to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/333d5abb369e243885a2dab25f47912c to your computer and use it in GitHub Desktop.
A custom context manager for RGB classes with exception tracking
class ExceptionCounter:
""" Custom context manager class counting exceptions """
def __init__(self):
self.count = 0
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if exc_type and exc_value:
self.count += 1
# suppress it
return True
def test_attributes(klass):
""" Test attribute validation for a RGB color class """
counter = ExceptionCounter()
for attr,value in (('r','red'), ('g','green'), ('b','blue')):
with counter:
# init value error
klass(500, 500, 500)
with counter:
# type error
setattr(klass(), attr, value)
with counter:
# value error
setattr(klass(), attr, 500)
print(counter.count)
assert(counter.count == 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment