ColorHash
ColorHash is a lightweight Python library for generating deterministic colors from any object. By calculating a color value based on an object's hash, it ensures consistent results: the same input will always yield the same color. It is currently at version 2.3.0 and has an active development cycle, with recent updates focusing on performance and wider Python version compatibility.
Common errors
-
Colors generated for different inputs are too similar.
cause The default or custom `lightness`, `saturation`, or `hue` ranges provided to the `ColorHash` constructor are too restrictive, limiting the available color spectrum for differentiation.fixExpand the sequences of `lightness` and `saturation` values (e.g., `lightness=[0.2, 0.4, 0.6, 0.8]`), or widen the `min_h`/`max_h` hue range to allow `ColorHash` more options to deterministically select a distinct color. -
AttributeError: 'ColorHash' object has no attribute 'color' (or similar for other missing attributes).
cause Attempting to access color information using an incorrect or non-existent attribute name on the `ColorHash` object. The library provides specific attributes for color representations.fixUse the correct attributes to retrieve the desired color format: `c.hex` for hexadecimal string, `c.rgb` for an RGB tuple, or `c.hsl` for an HSL tuple.
Warnings
- breaking Version 2.0.0 introduced exposure of parameters to influence colors (lightness, saturation, hue ranges) and runtime validation of input parameters. Code relying on implicit color generation or passing non-standard values might encounter new validation errors or altered color outputs.
- deprecated As of version 2.1.0, Python 3.7 is no longer officially tested. While it 'shall work', future compatibility or undetected bugs might arise for users on Python 3.7. The library officially supports Python 3.8+.
- gotcha Setting very narrow or identical ranges for `lightness`, `saturation`, or `hue` during `ColorHash` initialization can result in multiple different input objects generating colors that are almost indistinguishable.
Install
-
pip install colorhash
Imports
- ColorHash
from colorhash import ColorHash
Quickstart
from colorhash import ColorHash
# Generate a color for a string
c = ColorHash('Hello World')
# Access color representations
print(f"HSL: {c.hsl}") # (Hue, Saturation, Lightness)
print(f"RGB: {c.rgb}") # (Red, Green, Blue)
print(f"Hex: {c.hex}") # Hexadecimal color string
# Customize color generation (e.g., specific lightness range)
c_custom = ColorHash('Another Object', lightness=[0.2, 0.4, 0.6])
print(f"Custom Hex: {c_custom.hex}")