mirror of
https://github.com/catppuccin/python.git
synced 2026-02-04 20:07:47 +08:00
feat: Add from hex method
This commit is contained in:
parent
e439afbdf3
commit
bef684afd4
@ -1,8 +1,11 @@
|
||||
"""
|
||||
Functionality relating to individual colours.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Tuple
|
||||
from typing import Tuple, Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@ -16,9 +19,25 @@ class Colour:
|
||||
@property
|
||||
def rgb(self) -> Tuple[int, int, int]:
|
||||
"""Get the colour as a 3-tuple of red, green, and blue."""
|
||||
return (self.red, self.green, self.blue)
|
||||
return self.red, self.green, self.blue
|
||||
|
||||
@property
|
||||
def hex(self) -> str:
|
||||
"""Get the colour as a lowercase hex string."""
|
||||
return f"{self.red:02x}{self.green:02x}{self.blue:02x}"
|
||||
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
if not isinstance(other, Colour):
|
||||
raise ValueError("Cannot check equality with non-colour types.")
|
||||
return self.hex == other.hex
|
||||
|
||||
@classmethod
|
||||
def from_hex(cls, hex_string: str) -> Colour:
|
||||
"""Create a color from hex string."""
|
||||
if len(hex_string) != 6:
|
||||
raise ValueError("Hex string must be 6 characters long.")
|
||||
match = re.match(r"([\da-fA-F]{2})" * 3, hex_string)
|
||||
if match is None:
|
||||
raise ValueError("Hex string have an invalid format.")
|
||||
r, g, b = match.groups()
|
||||
return Colour(*(int(col, 16) for col in (r, g, b)))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user