Created
March 12, 2026 05:03
-
-
Save pythonhacker/57f7153340f7f6b6e0490eddd9054978 to your computer and use it in GitHub Desktop.
RGB Color class with validation using attrs package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}") | |
| @attrs.define | |
| class ColorAttrs: | |
| r: int = attrs.field(validator=rgb_validator, default=0) | |
| g: int = attrs.field(validator=rgb_validator, default=0) | |
| b: int = attrs.field(validator=rgb_validator, default=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment