Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created March 12, 2026 04:50
Show Gist options
  • Select an option

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

Select an option

Save pythonhacker/b1ea624deac8ece797138e4c02197723 to your computer and use it in GitHub Desktop.
RGB Color class with validation using a custom descriptor
class IntRange:
""" Custom integer range class using descriptors """
def __init__(self, min_val, max_val):
self._range = range(min_val, max_val)
def __set_name__(self, owner, name):
self.name = "_" + name
def __get__(self, obj, objtype=None):
return getattr(obj, self.name)
def __set__(self, obj, value):
if not isinstance(value, int):
raise TypeError("Error - must be integer")
if not value in self._range:
raise ValueError(f"{value} not in range {self._range}")
setattr(obj, self.name, value)
class ColorDesc(Color):
r = IntRange(0, 255)
g = IntRange(0, 255)
b = IntRange(0, 255)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment