Utility Functions API

This document covers all utility functions available in Colorium.

Validation Functions

is_hex

1
def is_hex(char: str) -> bool

Check if a character is a valid hexadecimal digit.

Parameters:

ParameterTypeDescription
charstrCharacter to check

Returns: True if character is a valid hex digit, False otherwise

Example:

1
2
3
4
5
from colorium.utils import is_hex

print(is_hex('F'))  # True
print(is_hex('G'))  # False
print(is_hex('5'))  # True

Math Functions

clamp

1
def clamp(value: float, min_value: float = 0.0, max_value: float = 1.0) -> float

Clamp a value between a minimum and maximum.

Parameters:

ParameterTypeDescription
valuefloatValue to clamp
min_valuefloatMinimum allowed value (default: 0.0)
max_valuefloatMaximum allowed value (default: 1.0)

Returns: Clamped value

Example:

1
2
3
4
5
6
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)) # 3

round_decimal

1
def round_decimal(value: float, decimals: int = 2) -> float

Round a float to specified decimal places.

Parameters:

ParameterTypeDescription
valuefloatValue to round
decimalsintNumber of decimal places (default: 2)

Returns: Rounded float

Example:

1
2
3
4
from colorium.utils import round_decimal

print(round_decimal(3.14159, 2))  # 3.14
print(round_decimal(3.14159, 4))  # 3.1416

String Functions

to_hex

1
def to_hex(value: int) -> str

Convert an integer to a two-digit hexadecimal string.

Parameters:

ParameterTypeDescription
valueintInteger value (0-255)

Returns: Two-digit hex string

Example:

1
2
3
4
5
6
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))  # 80

parse_percentage

1
def parse_percentage(value: str) -> float

Parse a percentage string to a float.

Parameters:

ParameterTypeDescription
valuestrPercentage string (e.g., "50%", "75%")

Returns: Float value (0.0-1.0 for percentages)

Example:

1
2
3
4
5
6
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.0

trim_string

1
def trim_string(value: str) -> str

Remove leading and trailing whitespace from a string.

Parameters:

ParameterTypeDescription
valuestrString to trim

Returns: Trimmed string

Example:

1
2
3
4
5
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

1
def _linearize_srgb(c: float) -> float

Convert sRGB (non-linear) to linear RGB.

Parameters:

ParameterTypeDescription
cfloatsRGB value (0-1)

Returns: Linear RGB value

Example:

1
2
3
from colorium.converters import _linearize_srgb

print(_linearize_srgb(0.5))  # 0.214041

_to_srgb

1
def _to_srgb(c: float) -> float

Convert linear RGB to sRGB (non-linear).

Parameters:

ParameterTypeDescription
cfloatLinear RGB value

Returns: sRGB value (0-1)

Example:

1
2
3
from colorium.converters import _to_srgb

print(_to_srgb(0.214041))  # 0.5

Constant Functions

get_color_hex

1
def get_color_hex(name: str) -> Optional[str]

Get hex value for a named color.

Parameters:

ParameterTypeDescription
namestrNamed color (case-insensitive)

Returns: Hex string or None

Example:

1
2
3
4
5
from colorium.constants import get_color_hex

print(get_color_hex("red"))    # ff0000
print(get_color_hex("BLUE"))   # 0000ff
print(get_color_hex("invalid")) # None

get_color_names

1
def get_color_names() -> List[str]

Get list of all named colors.

Returns: List of color names

Example:

1
2
3
4
5
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
def benchmark(func, *args, iterations: int = 1000) -> float

Benchmark a function execution time.

Parameters:

ParameterTypeDescription
funccallableFunction to benchmark
*argsanyFunction arguments
iterationsintNumber of iterations (default: 1000)

Returns: Average execution time in seconds

Example:

1
2
3
4
5
6
7
8
9
10
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

1
def profile(func, *args) -> Dict[str, float]

Profile a function execution.

Parameters:

ParameterTypeDescription
funccallableFunction to profile
*argsanyFunction arguments

Returns: Dictionary with timing information

Example:

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
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)  # FF

Error Handling

1
2
3
4
5
6
7
8
9
10
11
12
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.0

Validation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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"))  # False

Next Steps


Previous: Filter Classes Next: Changelog →

On this page
25 sections