On this page
  1. colorsys
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Generating an Evenly Spaced Hex Palette
  7. Gotchas & Boundaries
  8. Common Functions

colorsys

Prev: collections | Up: stdlib_module | Next: compileall
Rel: wave, gettext, locale, turtle, turtledemo
Ref: docs.python.org — colorsys
Tags: #public #python3 #stdlib


Import

import colorsys

Overview

Bidirectional color-space conversions between RGB and YIQ, HLS (Hue-Lightness-Saturation), and HSV (Hue-Saturation-Value). Reach for colorsys when generating color palettes, adjusting brightness/saturation programmatically, or converting UI/CSS colors without installing Pillow or NumPy.

Quick Start

import colorsys

# All inputs and outputs are floats in [0.0, 1.0]
h, s, v = colorsys.rgb_to_hsv(1.0, 0.0, 0.0)   # pure red
assert (round(h, 2), round(s, 2), round(v, 2)) == (0.0, 1.0, 1.0)

r, g, b = colorsys.hsv_to_rgb(h, s, 0.5)       # 50% darker red
assert (round(r, 2), round(g, 2), round(b, 2)) == (0.5, 0.0, 0.0)

Implementation Walkthrough

1. Generating an Evenly Spaced Hex Palette

Step around the hue wheel in HLS space (h in [0, 1)) and scale RGB channels to 0..255:

import colorsys

def hex_palette(count: int, lightness: float = 0.5, saturation: float = 0.75) -> list[str]:
    colors = []
    for i in range(count):
        r, g, b = colorsys.hls_to_rgb(i / count, lightness, saturation)
        colors.append(f"#{round(r * 255):02x}{round(g * 255):02x}{round(b * 255):02x}")
    return colors

palette = hex_palette(4)
assert len(palette) == 4 and all(c.startswith("#") and len(c) == 7 for c in palette)

Gotchas & Boundaries

Common Functions

Linked from

Related notes