Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save pythonhacker/5b8d88c81e07c0489305cd5ce881132c to your computer and use it in GitHub Desktop.
RGB Color class using namedtuple with validation
from collections import namedtuple
class ColorTuple(namedtuple("ColorBase", "r g b")):
# prevents creation of instance __dict__
__slots__ = ()
def __new__(cls, r=0, g=0, b=0):
for v in (r, g, b):
if not isinstance(v, int):
raise TypeError("RGB values must be integers")
if not 0 <= v <= 255:
raise ValueError("RGB values must be between 0 and 255")
return super().__new__(cls, r, g, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment