v1.0.0
Utility Functions API
This document covers all utility functions available in Colorium.
Validation Functions
is_hex
def is_hex(char: str) -> boolCheck if a character is a valid hexadecimal digit.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| char | str | Character to check |
Returns: True if character is a valid hex digit, False otherwise
Example:
from colorium.utils import is_hex
print(is_hex('F')) # True
print(is_hex('G')) # False
print(is_hex('5')) # TrueMath Functions
clamp
def clamp(value: float, min_value: float = 0.0, max_value: float = 1.0) -> floatClamp a value between a minimum and maximum.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| value | float | Value to clamp |
| min_value | float | Minimum allowed value (default: 0.0) |
| max_value | float | Maximum allowed value (default: 1.0) |
Returns: Clamped value
Example:
from colorium.utils import clamp
print(clamp(0.5)) # 0.5
print(clamp(1.5)) # 1.0
print(clamp(-0.5)) # 0.0
print(clamp(5, 0, 3)) # 3round_decimal
def round_decimal(value: float, decimals: int = 2) -> floatRound a float to specified decimal places.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| value | float | Value to round |
| decimals | int | Number of decimal places (default: 2) |
Returns: Rounded float
Example:
from colorium.utils import round_decimal
print(round_decimal(3.14159, 2)) # 3.14
print(round_decimal(3.14159, 4)) # 3.1416String Functions
to_hex
def to_hex(value: int) -> strConvert an integer to a two-digit hexadecimal string.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| value | int | Integer value (0-255) |
Returns: Two-digit hex string
Example:
from colorium.utils import to_hex
print(to_hex(0)) # 00
print(to_hex(255)) # FF
print(to_hex(10)) # 0A
print(to_hex(128)) # 80parse_percentage
def parse_percentage(value: str) -> floatParse a percentage string to a float.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| value | str | Percentage string (e.g., "50%", "75%") |
Returns: Float value (0.0-1.0 for percentages)
Example:
from colorium.utils import parse_percentage
print(parse_percentage("50%")) # 0.5
print(parse_percentage("100%")) # 1.0
print(parse_percentage("75.5%")) # 0.755
print(parse_percentage("1.0")) # 1.0trim_string
def trim_string(value: str) -> strRemove leading and trailing whitespace from a string.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| value | str | String to trim |
Returns: Trimmed string
Example:
from colorium.utils import trim_string
print(trim_string(" hello ")) # hello
print(trim_string("hello")) # hello
print(trim_string(" ")) #Color Space Helper Functions
_linearize_srgb
def _linearize_srgb(c: float) -> floatConvert sRGB (non-linear) to linear RGB.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| c | float | sRGB value (0-1) |
Returns: Linear RGB value
Example:
from colorium.converters import _linearize_srgb
print(_linearize_srgb(0.5)) # 0.214041_to_srgb
def _to_srgb(c: float) -> floatConvert linear RGB to sRGB (non-linear).
Parameters:
| Parameter | Type | Description |
|---|---|---|
| c | float | Linear RGB value |
Returns: sRGB value (0-1)
Example:
from colorium.converters import _to_srgb
print(_to_srgb(0.214041)) # 0.5Constant Functions
get_color_hex
def get_color_hex(name: str) -> Optional[str]Get hex value for a named color.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| name | str | Named color (case-insensitive) |
Returns: Hex string or None
Example:
from colorium.constants import get_color_hex
print(get_color_hex("red")) # ff0000
print(get_color_hex("BLUE")) # 0000ff
print(get_color_hex("invalid")) # Noneget_color_names
def get_color_names() -> List[str]Get list of all named colors.
Returns: List of color names
Example:
from colorium.constants import get_color_names
names = get_color_names()
print(len(names)) # 147
print(names[:5]) # ['AliceBlue', 'AntiqueWhite', 'Aqua', 'Aquamarine', 'Azure']Utility Class Example
ColorUtils
from colorium import Color
from colorium.utils import clamp, to_hex, parse_percentage
class ColorUtils:
"""Collection of color utility functions"""
@staticmethod
def adjust_brightness(color: Color, amount: float) -> Color:
"""Adjust brightness safely"""
amount = clamp(amount, -1.0, 1.0)
result = color.clone()
if amount > 0:
result.lighter(amount)
else:
result.darker(-amount)
return result
@staticmethod
def adjust_saturation(color: Color, amount: float) -> Color:
"""Adjust saturation safely"""
amount = clamp(amount, -1.0, 1.0)
result = color.clone()
if amount > 0:
result.saturate(amount)
else:
result.desaturate(-amount)
return result
@staticmethod
def create_hex_from_rgb(r: int, g: int, b: int) -> str:
"""Create hex string from RGB values"""
return f"#{to_hex(r)}{to_hex(g)}{to_hex(b)}"
@staticmethod
def parse_color_string(color_str: str) -> Optional[Color]:
"""Parse color string with percentage support"""
from colorium import from_string
return from_string(color_str)Example:
from colorium import Color
from colorium.utils import ColorUtils
color = Color(100, 150, 200)
# Adjust brightness
brighter = ColorUtils.adjust_brightness(color, 0.3)
# Create hex
hex_str = ColorUtils.create_hex_from_rgb(255, 0, 0)
print(hex_str) # #FF0000
# Parse color
parsed = ColorUtils.parse_color_string("red")Performance Functions
benchmark
def benchmark(func, *args, iterations: int = 1000) -> floatBenchmark a function execution time.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| func | callable | Function to benchmark |
| *args | any | Function arguments |
| iterations | int | Number of iterations (default: 1000) |
Returns: Average execution time in seconds
Example:
from colorium.utils import benchmark
from colorium import Color
color = Color(100, 150, 200)
def test_to_hex():
return color.to_hex_string()
avg_time = benchmark(test_to_hex, iterations=10000)
print(f"Average time: {avg_time:.6f}s")profile
def profile(func, *args) -> Dict[str, float]Profile a function execution.
Parameters:
| Parameter | Type | Description |
|---|---|---|
| func | callable | Function to profile |
| *args | any | Function arguments |
Returns: Dictionary with timing information
Example:
from colorium.utils import profile
from colorium import Color
color = Color(100, 150, 200)
def test_operations():
color.clone().lighter(0.2).saturate(0.3).to_hex_string()
result = profile(test_operations)
print(f"Time: {result['time']:.6f}s")Best Practices
Using Utilities
from colorium.utils import clamp, to_hex
# Good - use utilities
rgb_value = clamp(300, 0, 255) # 255
hex_str = to_hex(255) # FF
# Avoid - manual implementation
rgb_value = max(0, min(300, 255)) # 255
hex_str = hex(255)[2:].upper().zfill(2) # FFError Handling
from colorium.utils import parse_percentage
def safe_parse_percentage(value: str) -> float:
"""Safely parse percentage with fallback"""
try:
return parse_percentage(value)
except ValueError:
return 0.0
# Usage
print(safe_parse_percentage("50%")) # 0.5
print(safe_parse_percentage("abc")) # 0.0Validation
from colorium.utils import is_hex, trim_string
def validate_color_input(value: str) -> bool:
"""Validate color input string"""
value = trim_string(value)
# Check if it's a hex color
if value.startswith('#'):
hex_value = value[1:]
return len(hex_value) in (3, 6) and all(is_hex(c) for c in hex_value)
# Check if it's a named color
from colorium import NAMED_COLORS
return value.lower() in NAMED_COLORS
# Usage
print(validate_color_input("#FF0000")) # True
print(validate_color_input("red")) # True
print(validate_color_input("#GGGGGG")) # FalseNext Steps
- Color Class — Color class API
- Color Functions — Factory functions
- Filter Classes — Filter API
Previous: Filter Classes Next: Changelog →