webcolors

repository·trunk·Indexed 41 days ago

https://github.com/ubernostrum/webcolors

A Python library for converting between HTML and CSS color formats, including hex, RGB integer and percentage triplets, and named colors from HTML 4, CSS2, CSS2.1, and CSS3. Version 25.10.0 provides tools for normalization, HTML5 color parsing and serialization, and strict conformance to web standards. It focuses on the RGB colorspace and does not support HSL, alpha-channels (RGBA/HSLA), or CSS Color Module Level 4.

Tokens
7.5K
Snippets
30
Records
48
Agent score
48%

What's inside webcolors

  1. Overview of webcolors functionality

    trunk

    webcolors is a Python module designed for working with and converting between various HTML/CSS color formats. It supports normalization and conversion within the RGB colorspace for the following formats:

    • Specification-defined color names
    • Six-digit hexadecimal
    • Three-digit hexadecimal
    • Integer rgb() triplets
    • Percentage rgb() triplets

    Note: For conversions involving HSL, you should use the colorsys module from the Python standard library, as webcolors focuses on the RGB colorspace.

    import webcolors
    webcolors.hex_to_name("#daa520")
    # 'goldenrod'
  2. Supported color formats in webcolors

    trunk

    The webcolors module supports conversions between several sRGB color specification methods.

    Supported formats:

    • Six-digit hexadecimal: e.g., #0099cc
    • Three-digit hexadecimal: e.g., #09c (expanded to #0099cc)
    • Integer rgb() triplet: e.g., rgb(0, 153, 204)
    • Percentage rgb() triplet: e.g., rgb(0%, 60%, 80%)
    • Named colors: Includes defined names from HTML 4, CSS2, CSS2.1, and CSS3.

    Unsupported formats:

    • CSS1 named colors: These lacked defined values in the standard.
    • CSS2 system colors: These had no fixed values (dependent on the OS).
    • The transparent keyword.
    • Alpha-channel/Opacity: Formats using rgba() or hsla() are not supported.
    • HSL color space: Formats using hsl() or hsla() are not supported.

    If you need to work with HSL or other color systems, use the Python standard library's colorsys module.

  3. Convert between HTML/CSS color formats with webcolors

    trunk

    The webcolors module provides tools for normalizing and converting between various HTML/CSS color formats within the RGB colorspace.

    Supported formats include:

    • Specification-defined color names
    • Six-digit hexadecimal
    • Three-digit hexadecimal
    • Integer rgb() triplets
    • Percentage rgb() triplets

    Note: For conversions involving HSL, use the colorsys module from the Python standard library, as webcolors focuses on the RGB colorspace.

    import webcolors
    # Convert hex to name
    webcolors.hex_to_name("#daa520")  # Returns 'goldenrod'
  4. Verify color conversion consistency

    trunk

    To ensure mathematical correctness across different color formats, webcolors performs exhaustive testing of its conversion functions.

    For hexadecimal and integer rgb() formats, the library verifies all 16,777,216 possible color values to ensure hex_to_rgb and rgb_to_hex are perfect inverses.

    Because floating-point precision makes exact verification of percentage-based rgb() values impossible, the library instead verifies consistency. It ensures that for any integer triplet t, converting to a percentage and back to an integer returns the original value:

    t == rgb_percent_to_rgb(rgb_to_rgb_percent(t))

  5. Use webcolors data types for color representation

    trunk

    While you can pass plain 3-tuples to most functions, webcolors provides NamedTuple instances for richer representation. Functions that return triplets or simple colors will return these types.

    Supported types include:

    • IntegerRGB: For integer-based RGB triplets.
    • PercentRGB: For percentage-based RGB triplets.
    • HTML5SimpleColor: For HTML5 simple colors.

    Type aliases available for annotations:

    • IntTuple
    • PercentTuple
  6. Handle hexadecimal color values

    trunk

    When providing hexadecimal colors to webcolors functions, you can use strings in the following formats:

    • # followed by three hexadecimal digits (e.g., #ABC).
    • # followed by six hexadecimal digits (e.g., #AABBCC).

    Digits A-F are case-insensitive in input. However, for output or intermediate conversions, webcolors always normalizes hexadecimal values to a lowercase format: # followed by six lowercase hexadecimal digits (e.g., #aabbcc).

    You can manually normalize a hex string using webcolors.normalize_hex.

    # Example of expected normalization behavior
    # Input can be uppercase or mixed, but output is lowercase 6-digit hex
    normalized = webcolors.normalize_hex("#AABBCC") # returns '#aabbcc'
  7. Work with RGB triplets (Integer and Percentage)

    trunk

    The library handles two types of RGB triplets:

    1. Integer RGB: Represented as a 3-tuple of Python int. Use webcolors.IntegerRGB for a named tuple representation.
    2. Percentage RGB: Represented as a 3-tuple of Python str (e.g., ('50%', '10%', '0%')). Use webcolors.PercentRGB for a named tuple representation.

    Normalization Rules (CSS Clipping): When using functions that process triplets, values are automatically clipped to valid CSS ranges:

    • Integers: Values < 0 become 0; values > 255 become 255.
    • Percentages: Values < 0% become 0%; values > 100% become 100%.
    • Negative Zero: -0 and -0% are normalized to 0 and 0%.

    You can manually normalize these using webcolors.normalize_integer_triplet or webcolors.normalize_percent_triplet.

    # Using named tuples for triplets
    int_rgb = webcolors.IntegerRGB(255, 0, 0)
    percent_rgb = webcolors.PercentRGB('100%', '0%', '0%')
  8. Precision limitations in RGB percentage conversions

    trunk

    Due to the nature of IEEE floating-point representation in Python, conversions between integer and percentage rgb() triplets via rgb_to_rgb_percent and rgb_percent_to_rgb may exhibit imprecision.

    To mitigate this, webcolors handles several common values as special cases with hard-coded precise results:

    • 255, 128, 64, 32, 16, and 0

    For all other values, the conversion to a percentage rgb() triplet uses a standard Python float, rounded to two decimal places.

  9. Converting between RGB and HSL

    trunk

    The webcolors module does not provide native HSL conversion functions. Instead, it is designed to work alongside Python's built-in colorsys module.

    To convert colors between RGB and HSL, you should use the integer RGB triplets provided by webcolors and pass them to colorsys functions.

  10. Verify color definition correctness

    trunk

    The webcolors library maintains conformance to web standards by verifying its internal color mappings against official documentation. The verification process (performed via tests/definitions.py) checks the following:

    • HTML4: Validates that webcolors.HTML4_NAMES_TO_HEX matches the 16 named colors in the HTML 4 standard.
    • CSS2.1: Validates that webcolors.CSS21_NAMES_TO_HEX matches the 17 named colors in the CSS2.1 standard.
    • CSS3/SVG: Validates that webcolors.CSS3_NAMES_TO_HEX matches the 147 named colors in the CSS3 color module and ensures webcolors.name_to_rgb returns the correct integer values.
  11. Handling American vs British color spellings

    trunk

    CSS3 defines multiple color names with identical values to support both American and British spellings (e.g., "gray" vs "grey").

    When converting from a name to another format (using name_to_hex, name_to_rgb, or name_to_rgb_percent), webcolors accepts either spelling as long as the spec argument is set to webcolors.CSS3.

    When converting from a format to a name, webcolors consistently returns the American spelling (e.g., "gray") to maintain consistency with HTML 4, CSS1, and CSS2. The following variants are affected:

    • "darkgray" / "darkgrey"
    • "darkslategray" / "darkslategrey"
    • "dimgray" / "dimgrey"
    • "gray" / "grey"
    • "lightgray" / "lightgrey"
    • "lightslategray" / "lightslategrey"
    • "slategray" / "slategrey"