API reference¶
The contents of the webcolors module fall into five categories:
A set of (optional) data types for representing color values.
Constants for several purposes.
Normalization functions which sanitize input in various formats prior to conversion or output.
Conversion functions between each method of specifying colors.
Implementations of the color parsing and serialization algorithms in HTML5.
See the documentation regarding conventions for
information regarding the types and representation of various color formats in
webcolors.
All conversion functions which involve color names take an optional argument to determine the specification from which to draw color names. See the set of specification identifiers for valid values.
All conversion functions, when faced with identifiably invalid hexadecimal
color values, or with a request to name a color which has no name in the
requested specification, or with an invalid specification identifier, will
raise ValueError.
Imports and submodules
The public, supported API of webcolors is exported from its top-level
module, webcolors. Although the codebase is internally organized into
several submodules for easier maintenance, the existence, names, and
organization of these submodules is not part of webcolors’ supported
API and cannot be relied upon.
For example: although normalize_hex() is actually implemented in a
submodule named webcolors._normalization, it must always be referred to
as webcolors.normalize_hex, never as
webcolors._normalization.normalize_hex.
Data types¶
Integer and percentage rgb() triplets, and HTML5 simple colors, can be
passed to functions in webcolors as plain 3-tuple of the
appropriate data type. But the following NamedTuple instances
are also provided to represent these types more richly, and functions in
webcolors which return triplets or simple colors will return instances of
these:
- class webcolors.IntegerRGB(red: int, green: int, blue: int)[source]¶
NamedTuplerepresenting an integer RGB triplet.Has three fields, each of type
intand in the range 0-255 inclusive:- red¶
The red portion of the color value.
- green¶
The green portion of the color value.
- blue¶
The blue portion of the color value.
- class webcolors.PercentRGB(red: str, green: str, blue: str)[source]¶
NamedTuplerepresenting a percentage RGB triplet.Has three fields, each of type
strand representing a percentage value in the range 0%-100% inclusive:- red¶
The red portion of the color value.
- green¶
The green portion of the color value.
- blue¶
The blue portion of the color value.
- class webcolors.HTML5SimpleColor(red: int, green: int, blue: int)[source]¶
NamedTuplerepresenting an HTML5 simple color.Has three fields, each of type
intand in the range 0-255 inclusive:- red¶
The red portion of the color value.
- green¶
The green portion of the color value.
- blue¶
The blue portion of the color value.
Additionally, to aid in type annotations, the following type aliases are defined, and used throughout this module:
- webcolors.IntTuple¶
alias of
IntegerRGB|HTML5SimpleColor|Tuple[int,int,int]
- webcolors.PercentTuple¶
alias of
PercentRGB|Tuple[str,str,str]
Constants¶
The following constants are available for indicating the specification from which to draw color name choices, in functions which can work with multiple specifications.
- webcolors.CSS2¶
Represents the CSS2 specification. Value is
"css2".
- webcolors.CSS21¶
Represents the CSS2.1 specification. Value is
"css21".
- webcolors.CSS3¶
Represents the CSS3 specification. Value is
"css3".
- webcolors.HTML4¶
Represents the HTML 4 specification. Value is
"html4".
Informative functions¶
- webcolors.names(spec: str = 'css3') List[str][source]¶
Return the list of valid color names for the given specification.
The color names will be normalized to all-lowercase, and will be returned in alphabetical order.
Note
Spelling variants
Some values representing named gray colors can map to either of two names in CSS3, because it supports both
"gray"and"grey"spelling variants for those colors. Functions which produce a name from a color value in other formats all normalize to the"gray"spelling for consistency with earlier CSS and HTML specifications which only supported"gray". Here, however, all valid names are returned, including – for CSS3 – both variant spellings for each of the affected"gray"/"grey"colors.Examples:
>>> names(spec=HTML4) ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'purple', 'red', 'silver', 'teal', 'white', 'yellow'] >>> names(spec="CSS1") Traceback (most recent call last): ... ValueError: "CSS1" is not a supported specification ...
- Raises:
ValueError – when the given spec is not supported.
Normalization functions¶
- webcolors.normalize_hex(hex_value: str) str[source]¶
Normalize a hexadecimal color value to a string consisting of the character # followed by six lowercase hexadecimal digits (what HTML5 terms a “valid lowercase simple color”).
If the supplied value cannot be interpreted as a hexadecimal color value,
ValueErroris raised. See the conventions used by this module for information on acceptable formats for hexadecimal values.Examples:
>>> normalize_hex("#0099cc") '#0099cc' >>> normalize_hex("#0099CC") '#0099cc' >>> normalize_hex("#09c") '#0099cc' >>> normalize_hex("#09C") '#0099cc' >>> normalize_hex("#0099gg") Traceback (most recent call last): ... ValueError: '#0099gg' is not a valid hexadecimal color value. >>> normalize_hex("0099cc") Traceback (most recent call last): ... ValueError: '0099cc' is not a valid hexadecimal color value.
- Parameters:
hex_value – The hexadecimal color value to normalize.
- Raises:
ValueError – when the input is not a valid hexadecimal color value.
- webcolors.normalize_integer_triplet(rgb_triplet: IntegerRGB | HTML5SimpleColor | Tuple[int, int, int]) IntegerRGB[source]¶
Normalize an integer
rgb()triplet so that all values are within the range 0..255.Examples:
>>> normalize_integer_triplet((128, 128, 128)) IntegerRGB(red=128, green=128, blue=128) >>> normalize_integer_triplet((0, 0, 0)) IntegerRGB(red=0, green=0, blue=0) >>> normalize_integer_triplet((255, 255, 255)) IntegerRGB(red=255, green=255, blue=255) >>> normalize_integer_triplet((270, -20, -0)) IntegerRGB(red=255, green=0, blue=0)
- Parameters:
rgb_triplet – The percentage rgb() triplet to normalize.
- webcolors.normalize_percent_triplet(rgb_triplet: PercentRGB | Tuple[str, str, str]) PercentRGB[source]¶
Normalize a percentage
rgb()triplet so that all values are within the range 0%..100%.Examples:
>>> normalize_percent_triplet(("50%", "50%", "50%")) PercentRGB(red='50%', green='50%', blue='50%') >>> normalize_percent_triplet(("0%", "100%", "0%")) PercentRGB(red='0%', green='100%', blue='0%') >>> normalize_percent_triplet(("-10%", "-0%", "500%")) PercentRGB(red='0%', green='0%', blue='100%')
- Parameters:
rgb_triplet – The percentage rgb() triplet to normalize.
Conversions from color names to other formats¶
- webcolors.name_to_hex(name: str, spec: str = 'css3') str[source]¶
Convert a color name to a normalized hexadecimal color value.
The color name will be normalized to lower-case before being looked up.
Examples:
>>> name_to_hex("white") '#ffffff' >>> name_to_hex("navy") '#000080' >>> name_to_hex("goldenrod") '#daa520' >>> name_to_hex("goldenrod", spec=HTML4) Traceback (most recent call last): ... ValueError: "goldenrod" is not defined as a named color in html4.
- Parameters:
name – The color name to convert.
spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given name has no definition in the given spec.
- webcolors.name_to_rgb(name: str, spec: str = 'css3') IntegerRGB[source]¶
Convert a color name to a 3-
tupleofintsuitable for use in anrgb()triplet specifying that color.The color name will be normalized to lower-case before being looked up.
Examples:
>>> name_to_rgb("white") IntegerRGB(red=255, green=255, blue=255) >>> name_to_rgb("navy") IntegerRGB(red=0, green=0, blue=128) >>> name_to_rgb("goldenrod") IntegerRGB(red=218, green=165, blue=32)
- Parameters:
name – The color name to convert.
spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given name has no definition in the given spec.
- webcolors.name_to_rgb_percent(name: str, spec: str = 'css3') PercentRGB[source]¶
Convert a color name to a 3-
tupleof percentages suitable for use in anrgb()triplet specifying that color.The color name will be normalized to lower-case before being looked up.
Examples:
>>> name_to_rgb_percent("white") PercentRGB(red='100%', green='100%', blue='100%') >>> name_to_rgb_percent("navy") PercentRGB(red='0%', green='0%', blue='50%') >>> name_to_rgb_percent("goldenrod") PercentRGB(red='85.49%', green='64.71%', blue='12.5%')
- Parameters:
name – The color name to convert.
spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given name has no definition in the given spec.
Conversions from hexadecimal color values to other formats¶
- webcolors.hex_to_name(hex_value: str, spec: str = 'css3') str[source]¶
Convert a hexadecimal color value to its corresponding normalized color name, if any such name exists.
The hexadecimal value will be normalized before being looked up.
Note
Spelling variants
Some values representing named gray colors can map to either of two names in CSS3, because it supports both
"gray"and"grey"spelling variants for those colors. This function will always return the variant spelled"gray"(such as"lightgray"instead of"lightgrey"). See the documentation on name conventions for details.Examples:
>>> hex_to_name("#ffffff") 'white' >>> hex_to_name("#fff") 'white' >>> hex_to_name("#000080") 'navy' >>> hex_to_name("#daa520") 'goldenrod' >>> hex_to_name("#daa520", spec=HTML4) Traceback (most recent call last): ... ValueError: "#daa520" has no defined color name in html4.
- Parameters:
hex_value – The hexadecimal color value to convert.
spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given color has no name in the given spec, or when the supplied hex value is invalid.
- webcolors.hex_to_rgb(hex_value: str) IntegerRGB[source]¶
Convert a hexadecimal color value to a 3-
tupleofintsuitable for use in anrgb()triplet specifying that color.The hexadecimal value will be normalized before being converted.
Examples:
>>> hex_to_rgb("#fff") IntegerRGB(red=255, green=255, blue=255) >>> hex_to_rgb("#000080") IntegerRGB(red=0, green=0, blue=128)
- Parameters:
hex_value – The hexadecimal color value to convert.
- Raises:
ValueError – when the supplied hex value is invalid.
- webcolors.hex_to_rgb_percent(hex_value: str) PercentRGB[source]¶
Convert a hexadecimal color value to a 3-
tupleof percentages suitable for use in anrgb()triplet representing that color.The hexadecimal value will be normalized before being converted.
Examples:
>>> hex_to_rgb_percent("#ffffff") PercentRGB(red='100%', green='100%', blue='100%') >>> hex_to_rgb_percent("#000080") PercentRGB(red='0%', green='0%', blue='50%')
- Parameters:
hex_value – The hexadecimal color value to convert.
- Raises:
ValueError – when the supplied hex value is invalid.
Conversions from integer rgb() triplets to other formats¶
- webcolors.rgb_to_name(rgb_triplet: IntegerRGB | HTML5SimpleColor | Tuple[int, int, int], spec: str = 'css3') str[source]¶
Convert a 3-
tupleofint, suitable for use in anrgb()color triplet, to its corresponding normalized color name, if any such name exists.To determine the name, the triplet will be converted to a normalized hexadecimal value.
Note
Spelling variants
Some values representing named gray colors can map to either of two names in CSS3, because it supports both
"gray"and"grey"spelling variants for those colors. This function will always return the variant spelled"gray"(such as"lightgray"instead of"lightgrey"). See the documentation on name conventions for details.Examples:
>>> rgb_to_name((255, 255, 255)) 'white' >>> rgb_to_name((0, 0, 128)) 'navy'
- Parameters:
rgb_triplet – The
rgb()triplet.spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given color has no name in the given spec.
- webcolors.rgb_to_hex(rgb_triplet: IntegerRGB | HTML5SimpleColor | Tuple[int, int, int]) str[source]¶
Convert a 3-
tupleofint, suitable for use in anrgb()color triplet, to a normalized hexadecimal value for that color.Examples:
>>> rgb_to_hex((255, 255, 255)) '#ffffff' >>> rgb_to_hex((0, 0, 128)) '#000080'
- Parameters:
rgb_triplet – The
rgb()triplet.
- webcolors.rgb_to_rgb_percent(rgb_triplet: IntegerRGB | HTML5SimpleColor | Tuple[int, int, int]) PercentRGB[source]¶
Convert a 3-
tupleofint, suitable for use in anrgb()color triplet, to a 3-tupleof percentages suitable for use in representing that color.Note
Floating-point precision
This function makes some trade-offs in terms of the accuracy of the final representation. For some common integer values, special-case logic is used to ensure a precise result (e.g., integer 128 will always convert to
"50%", integer 32 will always convert to"12.5%"), but for all other values a standard Pythonfloatis used and rounded to two decimal places, which may result in a loss of precision for some values due to the inherent imprecision of IEEE floating-point numbers.Examples:
>>> rgb_to_rgb_percent((255, 255, 255)) PercentRGB(red='100%', green='100%', blue='100%') >>> rgb_to_rgb_percent((0, 0, 128)) PercentRGB(red='0%', green='0%', blue='50%') >>> rgb_to_rgb_percent((218, 165, 32)) PercentRGB(red='85.49%', green='64.71%', blue='12.5%')
- Parameters:
rgb_triplet – The
rgb()triplet.
Conversions from percentage rgb() triplets to other formats¶
- webcolors.rgb_percent_to_name(rgb_percent_triplet: PercentRGB | Tuple[str, str, str], spec: str = 'css3') str[source]¶
Convert a 3-
tupleof percentages, suitable for use in anrgb()color triplet, to its corresponding normalized color name, if any such name exists.To determine the name, the triplet will be converted to a normalized hexadecimal value.
Note
Spelling variants
Some values representing named gray colors can map to either of two names in CSS3, because it supports both
"gray"and"grey"spelling variants for those colors. This function will always return the variant spelled"gray"(such as"lightgray"instead of"lightgrey"). See the documentation on name conventions for details.Examples:
>>> rgb_percent_to_name(("100%", "100%", "100%")) 'white' >>> rgb_percent_to_name(("0%", "0%", "50%")) 'navy' >>> rgb_percent_to_name(("85.49%", "64.71%", "12.5%")) 'goldenrod'
- Parameters:
rgb_percent_triplet – The
rgb()triplet.spec – The specification from which to draw the list of color names. Default is
CSS3.
- Raises:
ValueError – when the given color has no name in the given spec.
- webcolors.rgb_percent_to_hex(rgb_percent_triplet: PercentRGB | Tuple[str, str, str]) str[source]¶
Convert a 3-
tupleof percentages, suitable for use in anrgb()color triplet, to a normalized hexadecimal color value for that color.Examples:
>>> rgb_percent_to_hex(("100%", "100%", "0%")) '#ffff00' >>> rgb_percent_to_hex(("0%", "0%", "50%")) '#000080' >>> rgb_percent_to_hex(("85.49%", "64.71%", "12.5%")) '#daa520'
- Parameters:
rgb_percent_triplet – The
rgb()triplet.
- webcolors.rgb_percent_to_rgb(rgb_percent_triplet: PercentRGB | Tuple[str, str, str]) IntegerRGB[source]¶
Convert a 3-
tupleof percentages, suitable for use in anrgb()color triplet, to a 3-tupleofintsuitable for use in representing that color.Some precision may be lost in this conversion. See the note regarding precision for
rgb_to_rgb_percent()for details.Examples:
>>> rgb_percent_to_rgb(("100%", "100%", "100%")) IntegerRGB(red=255, green=255, blue=255) >>> rgb_percent_to_rgb(("0%", "0%", "50%")) IntegerRGB(red=0, green=0, blue=128) >>> rgb_percent_to_rgb(("85.49%", "64.71%", "12.5%")) IntegerRGB(red=218, green=165, blue=32)
- Parameters:
rgb_percent_triplet – The
rgb()triplet.
HTML5 color algorithms¶
Warning
Previously there were two competing HTML5 standards: one from WHATWG, and one from W3C. The WHATWG version is now the sole official HTML5 standard, and so the functions documented below implement the HTML5 color algorithms as given in section 2.3.6 of the WHATWG HTML5 standard.
- webcolors.html5_parse_simple_color(value: str) HTML5SimpleColor[source]¶
Apply the HTML5 simple color parsing algorithm.
Examples:
>>> html5_parse_simple_color("#ffffff") HTML5SimpleColor(red=255, green=255, blue=255) >>> html5_parse_simple_color("#fff") Traceback (most recent call last): ... ValueError: An HTML5 simple color must be a string seven characters long.
- Parameters:
value (
str, which must consist of exactly the character"#"followed by six hexadecimal digits.) – The color to parse.- Raises:
ValueError – when the given value is not a Unicode string of length 7, consisting of exactly the character
#followed by six hexadecimal digits.
- webcolors.html5_serialize_simple_color(simple_color: IntegerRGB | HTML5SimpleColor | Tuple[int, int, int]) str[source]¶
Apply the HTML5 simple color serialization algorithm.
Examples:
>>> html5_serialize_simple_color((0, 0, 0)) '#000000' >>> html5_serialize_simple_color((255, 255, 255)) '#ffffff'
- Parameters:
simple_color – The color to serialize.
- webcolors.html5_parse_legacy_color(value: str) HTML5SimpleColor[source]¶
Apply the HTML5 legacy color parsing algorithm.
Note that, since this algorithm is intended to handle many types of malformed color values present in real-world Web documents, it is extremely forgiving of input, but the results of parsing inputs with high levels of “junk” (i.e., text other than a color value) may be surprising.
Examples:
>>> html5_parse_legacy_color("black") HTML5SimpleColor(red=0, green=0, blue=0) >>> html5_parse_legacy_color("chucknorris") HTML5SimpleColor(red=192, green=0, blue=0) >>> html5_parse_legacy_color("Window") HTML5SimpleColor(red=0, green=13, blue=0)
- Parameters:
value – The color to parse.
- Raises:
ValueError – when the given value is not a Unicode string, when it is the empty string, or when it is precisely the string
"transparent".