Colorzero
Colorzero is a Python library designed for simple and 'pythonic' color manipulation. It features a comprehensive `Color` class capable of converting between various color representations and calculating color differences. The library utilizes immutable `Color` objects, which are descendents of `namedtuple`, necessitating a specific approach to color manipulation. The current version is 2.0, last released in March 2021.
Common errors
-
AttributeError: can't set attribute
cause Attempting to modify a color component directly on an existing `Color` object (e.g., `my_color.red = 0.5`). `Color` instances are immutable.fixTo change a color, create a new `Color` instance by using arithmetic operators with manipulation classes (e.g., `from colorzero import Red; my_color = my_color + Red(0.1)`). -
ValueError: ...
cause The `Color` constructor was called with parameters that do not conform to any of its supported variants (e.g., invalid string format for a named color or hex code, or out-of-range numerical values for components).fixRefer to the `Color` class documentation for accepted constructor arguments and valid ranges for color components (e.g., RGB floats between 0.0 and 1.0, or byte values between 0 and 255).
Warnings
- gotcha Color objects are immutable (tuple descendents). You cannot directly modify their attributes (e.g., `my_color.red = 0.5`). Operations on a color return a *new* Color instance.
- gotcha Direct manipulation of color components via attribute assignment will raise an `AttributeError`. For example, `c.red = 0.5` will fail.
- gotcha Some conversions between color spaces may result in a certain amount of precision loss.
Install
-
pip install colorzero
Imports
- Color
from colorzero import Color
- Red, Green, Blue, Hue, Lightness, Saturation
from colorzero import Red, Green, Blue
Quickstart
from colorzero import Color, Green, Lightness
# Create a color from various inputs
red = Color('red')
blue = Color(0, 0, 1) # RGB floats (0.0-1.0)
magenta_html = Color('#ff00ff')
# Color objects are immutable; operations return new objects
c = Color('yellow')
print(f"Initial color: {c}")
# Add green component
c_more_green = c + Green(0.1)
print(f"After adding green: {c_more_green}")
# Reduce lightness by multiplying
c_darker = c_more_green * Lightness(0.5)
print(f"After making darker: {c_darker}")
# Convert to different representations
print(f"HTML: {c_darker.html}")
print(f"RGB bytes: {c_darker.rgb_bytes}")
print(f"HLS: {c_darker.hls}")