Skip to content

Instantly share code, notes, and snippets.

View pythonhacker's full-sized avatar
💭
Full Reset

Anand B Pillai pythonhacker

💭
Full Reset
View GitHub Profile
@pythonhacker
pythonhacker / color_perf.py
Last active March 12, 2026 05:44
Performance of creation various RGB color classes using timeit
import timeit
for klass in (Color, ColorAttr, ColorProp, ColorAttrCustom,
ColorDesc, ColorData, ColorTuple):
print(f"Class: {klass.__name__}")
code = f"{klass.__name__}(128, 128, 128)"
setup = f"from __main__ import {klass.__name__}"
print(timeit.timeit(stmt=code, number=1000_000, setup=setup))
@pythonhacker
pythonhacker / color_tuple.py
Last active March 12, 2026 05:29
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")
@pythonhacker
pythonhacker / color_attrs.py
Created March 12, 2026 05:03
RGB Color class with validation using attrs package
import attrs
def rgb_validator(inst, attr, value):
# Validate type
if type(value) is not int:
raise ValueError("RGB values must be integers")
# Validate range
if not value in range(0, 256):
raise ValueError("RGB values must be in range {0...255}")
@pythonhacker
pythonhacker / color_desc.py
Created March 12, 2026 04:50
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):
@pythonhacker
pythonhacker / color_attr_custom.py
Last active March 12, 2026 04:40
RGB Color class with a custom RGBColor attribute representing color
class RGBColor(int):
def __new__(cls, value):
if not value in range(0, 256):
raise ValueError("RGB values must be in range {0...255}")
# Create the integer instance
return super().__new__(cls, value)
class ColorAttrCustom(Color):
""" Color class with full attribute validation and custom color type """
@pythonhacker
pythonhacker / color_prop.py
Created March 12, 2026 04:28
RGB Color class using properties with validation
class ColorProp(Color):
""" RGB Color class using properties """
def validate_rgb(self, value):
# Validate type
if type(value) is not int:
raise ValueError("RGB values must be integers")
# Validate range
if not value in range(0, 256):
raise ValueError("RGB values must be in range {0...255}")
@pythonhacker
pythonhacker / color_attr.py
Last active March 12, 2026 04:16
RGB Color class with validation overriding __setattr__
class ColorAttr(Color):
""" Color class with attribute validation """
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
def __setattr__(self, name, value):
if name in ("r", "g", "b"):
from dataclasses import dataclass
@dataclass(frozen=True)
class ColorData:
r: int = 0
g: int = 0
b: int = 0
def __post_init__(self):
for v in (self.r, self.g, self.b):
@pythonhacker
pythonhacker / test_attribute_validation.py
Last active March 12, 2026 04:21
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
@pythonhacker
pythonhacker / color_simple.py
Last active March 11, 2026 16:53
A simple RGB color class with __init__ validation
class Color:
""" A class representing RGB colour """
def __init__(self, r=0, g=0, b=0):
for val in (r, g, b):
# Validate type
if type(val) is not int:
raise ValueError("RGB values must be integers")
# Validate range
if not val in range(0, 256):