Palette

Palettes to hold collections of colors that can be shared between projects.

The Palette class provides an easy way to manage your favorite colors in different projects. In this context, a palette should be understood as any collection of colors that can be grouped due to a common feature, not only colors that necessarily “look good” together.

Every color in a Palette has a name associated with it. If unnamed colors are better fit to your particular use case, you may want to use a StackPalette instead.

Examples

Create a palette:

>>> palette = Palette(red="#ff0000")

Add colors:

>>> palette.add("blue", "#0000ff")

Get the value of colors:

>>> palette.red
Hex('#ff0000')

Manipulate colors in the palette (see the color_class module for details on how this works):

>>> palette = palette * HSL(1, 0.5, 1)  # Desaturate the whole palette 50%
>>> palette
Palette(red=#bf4040, blue=#4040bf)

Remove colors:

>>> palette.remove("red")
>>> "red" in palette.color_names
False

Save a palette:

>>> palette.save(name="single_blue")

Load saved palettes:

>>> palette = Palette.load("single_blue")

Concatenate two palettes together:

>>> Palette(red="f00", blue="00f") & Palette(green="0f0", yellow="0ff")
Palette(red=#ff0000, blue=#0000ff, green=#00ff00, yellow=#00ffff)
class colorir.palette.Palette(colors=None, color_format=None, **color_kwargs)

Bases: PaletteBase

Class that holds colors values associated with names.

Examples

>>> palette = Palette(red="#ff0000") # Uses default color format
>>> palette.red
Hex('#ff0000')

For more examples see the documentation of the palette module.

Parameters:
property colors: List[ColorBase]

A list of all color values currently stored in the palette.

property color_names: List[str]

A list of all color names currently stored in the palette.

property color_format: ColorFormat

Color format specifying how the colors of this palette are stored.

classmethod load(palettes=None, palettes_dir=None, search_builtins=True, search_cwd=True, color_format=None, warnings=True)

Factory method that loads previously created palettes into a Palette instance.

A palette is a file containing json-formatted information about colors that ends with the ‘.palette’ extension. You should not create such files manually but rather through the Palette.save() method.

If multiple palettes define different color values under the same name, only the first one will be kept. You can define the order in which the palettes are loaded by ordering them in the palettes parameter. By default this occurrence logs a warning, but this behaviour can be changed through the warnings parameter.

Parameters:
  • palettes (str | List[str] | None) – List of palettes located in the location represented by palettes_dir that should be loaded by this Palette instance. Additionally may include built-in palettes such as ‘css’ if search_builtins is set to True. By default, loads all palettes found in the specified directory.

  • palettes_dir (str | None) – The directory from which the palettes specified in the palettes parameter will be loaded. Defaults to the value specified in config.DEFAULT_PALETTES_DIR.

  • search_builtins – Whether palettes may also include built-in palettes such as ‘css’ or ‘basic’.

  • search_cwd – Whether palettes may also include palettes located in the current working directory.

  • color_format (ColorFormat | None) – Color format specifying how the colors of this Palette should be stored. Defaults to the value specified in config.DEFAULT_COLOR_FORMAT.

  • warnings – Whether to emit a warning if two colors with the same name but different color values were found in the palettes.

Examples

Loads the default CSS palette:

>>> css_palette = Palette.load('css')

Loads both the basic and fluorescent palettes into a new palette:

>>> colorful = Palette.load(['basic', 'fluorescent'])
self & other

Join two palettes sequentially.

Repeated color names wil raise an exception.

Examples

>>> Palette(red="ff0000") & Palette(blue="0000ff")
Palette(red=#ff0000, blue=#0000ff)
get_color(name, fallback=<object object>)

Retrieves one or more colors from the Palette given their names.

Parameters:
  • name (str | List[str]) – One or more names of colors in this palette.

  • fallback – What to return instead of colors that are not found in the palette. By default, throws an exception.

Examples

>>> palette = Palette(red="#ff0000", blue="#0000ff")
>>> palette.get_color("red")
Hex('#ff0000')
>>> palette.get_color(["red", "blue"])
[Hex('#ff0000'), Hex('#0000ff')]
Returns:

A single ColorBase if name is a string or a list of ColorBase if name is a list of strings.

Return type:

ColorBase | List[ColorBase]

get_names(color)

Finds all names of the provided color in this Palette.

Compares the provided color to every color the Palette contains and returns the names of the colors that are equivalent to the one provided.

Parameters:

color (ColorBase | str | tuple) – The value of the color to be searched for. Can be an instance of any color_class class or, alternatively, a color-like object that resembles the color you want to search for.

Examples

>>> palette = Palette(red="#ff0000")
>>> palette.get_names(HSL(0, 1, 0.5))
['red']
add(name, color)

Adds a color to the palette.

Two colors with the same name but different values are invalid and can not coexist in a same Palette. You should therefore avoid reusing names of already existing colors.

Parameters:
  • name (str) – Name to be assigned to the new color.

  • color (ColorBase | str | tuple) – The value of the color to be created. Can be an instance of any color_class class or, alternatively, a color-like object that resembles the color you want to add.

Examples

Adding a new blue color to the palette:

>>> palette = Palette()
>>> palette.add("bestblue", "4287f5")
>>> palette.bestblue
Hex('#4287f5')
update(name, color)

Updates a color to a new value.

Parameters:
  • name (str) – Name of the color to be updated.

  • color (ColorBase | str | tuple) – The value of the color to be updated. Can be an instance of any color_class class or, alternatively, a color-like object that resembles the format of the color you want to update.

Examples

Create a slightly dark shade of red:

>>> palette = Palette(myred="dd0000")
>>> palette.myred
Hex('#dd0000')

Change it to be even a bit darker:

>>> palette.update("myred", "800000")
>>> palette.myred
Hex('#800000')
remove(name)

Removes a color from the palette.

Parameters:

name – Name of the color to be removed.

Examples

>>> palette = Palette(red=RGB(1, 0, 0))
>>> palette.remove("red")
>>> "red" in palette.color_names
False
save(name, palettes_dir=None)

Saves the changes made to this Palette instance.

If this method is not called after modifications made by Palette.add(), Palette.update() and Palette.remove(), the modifications on the palette will not be permanent.

Examples

Loads both the basic and fluorescent palettes into a new palette called ‘colorful’:

>>> colorful = Palette.load(['basic', 'fluorescent'])

Save the palette to the default palette directory:

>>> colorful.save(name='colorful')
to_stackpalette()

Converts this palette into a StackPalette.

to_dict()

Converts this palette into a python dict.

grayscale()

Returns a copy of this object but with its colors in grayscale.

Examples

>>> palette = Palette(red="ff0000", yellow="ffff00")
>>> palette.grayscale()
Palette(red=#7f7f7f, yellow=#f7f7f7)
most_similar(color, n=1, method='CIE76')

Finds the n most similar colors to color in this palette.

Parameters:
  • color (ColorBase | str | tuple) – The value of the color of reference.

  • n – How many colors to be retrieved from most similar to least. -1 means all colors will be returned.

  • method – Method for calculating color distance. See the documentation of the function color_dist.

Examples

>>> palette = Palette(red="#ff0000", blue="#0000ff")
>>> palette.most_similar("#880000")
('red', Hex('#ff0000'))
Returns:

A tuple (color_name, color) if n == 1 or a Palette if n != 1.

item in self

Returns `True if the color is found in the palette and False otherwise.

delattr(self, name, /)

Implement delattr(self, name).

format(self, format_spec, /)

Default object formatter.

self >= value

Return self>=value.

self > value

Return self>value.

~self

Returns a copy of the palette but with its colors inverted in RGB space.

Examples

>>> palette = Palette(red="ff0000", yellow="ffff00")
>>> ~palette
Palette(red=#00ffff, yellow=#0000ff)
iter(self)

Iterates over the colors in the palette.

self <= value

Return self<=value.

len(self)

Returns the number of colors in the palette.

self < value

Return self<value.

self != value

Return self!=value.

setattr(self, name, value, /)

Implement setattr(self, name, value).

sys.getsizeof(self)

Size of object in memory, in bytes.

blend(obj, perc=0.5, grad_class=<class 'colorir.gradient.Grad'>)
class colorir.palette.StackPalette(colors=None, color_format=None)

Bases: PaletteBase

Class that handles anonymous indexed colors stored as a stack.

This class may be used as a replacement for Palette when the name of the colors is irrelevant.

Examples

>>> spalette = StackPalette(["ff0000", "00ff00", "0000ff"])
>>> spalette[0]
Hex('#ff0000')
Parameters:
property colors: List[ColorBase]

A list of all color values currently stored in the StackPalette.

Type:

colors

property color_format: ColorFormat

Color format specifying how the colors of this palette are stored.

classmethod load(palettes=None, palettes_dir=None, search_builtins=True, search_cwd=True, color_format=None)

Factory method that loads previously created stack palettes into a StackPalette instance.

A stack palette is a file containing json-formatted information about colors that ends with the ‘.spalette’ extension. You should not create such files manually but rather through the StackPalette.save() method.

Examples

Load a stack palette called “project_interface” from the default directory:

>>> spalette = StackPalette.load("project_interface")  
Parameters:
  • palettes (str | List[str] | None) – List of stack palettes located in the location represented by palettes_dir that should be loaded by this StackPalette instance. By default, loads all palettes found in the specified directory.

  • palettes_dir (str | None) – The directory from which the palettes specified in the palettes parameter will be loaded. Defaults to the value specified in config.DEFAULT_PALETTES_DIR.

  • search_builtins – Whether palettes may also include built-in palettes such as ‘tab10’ or ‘dark2’.

  • search_cwd – Whether palettes may also include palettes located in the current working directory.

  • color_format (ColorFormat | None) – Color format specifying how the colors of this Palette should be stored. Defaults to the value specified in config.DEFAULT_COLOR_FORMAT.

classmethod new_complementary(n, color=None, color_format=None)

Creates a new palette with n complementary colors.

Colors are considered complementary if they are interspaced in the additive color wheel.

Examples

Make a palette from red and its complementary color, cyan:

>>> spalette = StackPalette.new_complementary(2, RGB(1, 0, 0))
>>> spalette
StackPalette([#ff0000, #00ffff])

Make a tetradic palette of random colors:

>>> spalette = StackPalette.new_complementary(4)
Parameters:
  • n (int) – The number of colors in the new palette.

  • color (ColorBase | str | tuple | None) – A color from which the others will be generated against. By default, a color is randomly chosen.

  • color_format (ColorFormat | None) – Color format specifying how the colors of this StackPalette should be stored. Defaults to the value specified in config.DEFAULT_COLOR_FORMAT.

classmethod new_analogous(n, sections=12, start=0, color=None, color_format=None)

Creates a new palette with n analogous colors.

Colors are considered analogous if they are side-by-side in the additive color wheel.

Examples

Make a palette from red and its analogous color, orange:

>>> spalette = StackPalette.new_analogous(2, start=1, color=RGB(1, 0, 0))
>>> spalette
StackPalette([#ff0000, #ff8000])

Make a palette of four similar colors:

>>> spalette = StackPalette.new_analogous(4, sections=24)
Parameters:
  • n (int) – The number of colors in the new palette.

  • sections – The number of sections in which the additive color wheel will be divided before sampling colors. The bigger this number, the more similar the colors will be.

  • start – Where the color described in the ‘color’ parameter will be placed with respect to the others. If ‘0’, ‘color’ will be in the center of the generated palette, and colors will be sampled from both its sides in the color wheel. If ‘1’, colors will be sampled clockwise from ‘color’. If ‘-1’, they will be sampled counter-clockwise.

  • color (ColorBase | str | tuple | None) – A color from which the others will be generated against. By default, a color is randomly chosen.

  • color_format (ColorFormat | None) – Color format specifying how the colors of this StackPalette should be stored. Defaults to the value specified in config.DEFAULT_COLOR_FORMAT.

self & other

Join two palettes sequentially.

Examples

>>> StackPalette(["ff0000"]) & StackPalette(["0000ff"])
StackPalette([#ff0000, #0000ff])
resize(n, repeat=False, grad_class=<class 'colorir.gradient.Grad'>, **kwargs)

Resizes the palette to be n elements long by interpolating or repeating colors.

Parameters:
  • repeat – If True, repeats the colors intead of interpolating them to reach the length goal.

  • grad_class – Which gradient class to use for interpolation.

  • n (int) – Number of elements in the final palette.

  • kwargs – Key-word arguments passed down to the internal gradient object.

Examples

>>> StackPalette(["000000", "ffffff"]).resize(3)
StackPalette([#000000, #777777, #ffffff])
>>> StackPalette(["000000", "ffffff"]).resize(3, repeat=True)
StackPalette([#000000, #ffffff, #000000])
Returns:

A resized copy of this stack palette.

add(color, i=None)

Adds a color to the end of the stack palette.

Parameters:
  • color (ColorBase | str | tuple) – The value of the color to be created. Can be an instance of any color_class class or, alternatively, a color-like object that resembles the color you want to add.

  • i – Index of the new color. It is added at the end of the palette by default.

Examples

Adding a new blue color to the palette:

>>> spalette = StackPalette()
>>> spalette.add("4287f5")
>>> spalette[0]
Hex('#4287f5')
update(index, color)

Updates a color to a new value.

Parameters:
  • index (int) – Index of the color to be updated.

  • color (ColorBase | str | tuple) – The value of the color to be updated. Can be an instance of any color_class class or, alternatively, a color-like object that resembles the format of the color you want to update.

Examples

Create a slightly dark shade of red:

>>> spalette = StackPalette(["dd0000"])
>>> spalette[0]
Hex('#dd0000')

Change it to be even a bit darker:

>>> spalette.update(0, "800000")
>>> spalette[0]
Hex('#800000')
remove()

Removes a color from the end of the palette.

Colors can only be removed from the last index of the stack palette, just like in a normal stack.

Examples

>>> spalette = StackPalette(["#ff0000"])
>>> "#ff0000" in spalette
True
>>> spalette.remove()
>>> "#ff0000" in spalette
False
save(name, palettes_dir=None)

Saves the changes made to this StackPalette instance.

If this method is not called after modifications made by StackPalette.add(), StackPalette.update() and StackPalette.remove(), the modifications on the palette will not be permanent.

Examples

Create a new StackPalette and save it to the current directory:

>>> spalette = StackPalette(["ff0000", "00ff00", "0000ff"])
>>> spalette.save(name="elementary")
to_palette(names)

Converts this stack palette into a Palette.

Parameters:

names (List[str]) – Names that will be given to the colors in the same order they appear in this stack palette.

grayscale()

Returns a copy of this object but with its colors in grayscale.

Examples

>>> spalette = StackPalette(["ff0000", "ffff00"])
>>> spalette.grayscale()
StackPalette([#7f7f7f, #f7f7f7])
most_similar(color, n=1, method='CIE76')

Finds the n most similar colors to color in this palette.

Parameters:
  • color (ColorBase | str | tuple) – The value of the color of reference.

  • n – How many colors to be retrieved from most similar to least. -1 means all colors will be returned.

  • method – Method for calculating color distance. See the documentation of color_dist.

Examples

>>> palette = StackPalette(["#ff0000", "#0000ff"])
>>> palette.most_similar("#880000")
Hex('#ff0000')
Returns:

A single color object if n == 1 or a StackPalette if n != 1.

item in self

Returns `True if the color is found in the palette and False otherwise.

delattr(self, name, /)

Implement delattr(self, name).

dir(self)

Default dir() implementation.

format(self, format_spec, /)

Default object formatter.

self >= value

Return self>=value.

self > value

Return self>value.

~self

Returns a copy of the palette but with its colors inverted in RGB space.

Examples

>>> palette = Palette(red="ff0000", yellow="ffff00")
>>> ~palette
Palette(red=#00ffff, yellow=#0000ff)
iter(self)

Iterates over the colors in the palette.

self <= value

Return self<=value.

len(self)

Returns the number of colors in the palette.

self < value

Return self<value.

self != value

Return self!=value.

setattr(self, name, value, /)

Implement setattr(self, name, value).

sys.getsizeof(self)

Size of object in memory, in bytes.

blend(obj, perc=0.5, grad_class=<class 'colorir.gradient.Grad'>)
colorir.palette.find_palettes(palettes_dir=None, search_builtins=True, search_cwd=True, kind=(<class 'colorir.palette.Palette'>, <class 'colorir.palette.StackPalette'>))

Returns the names of the palettes found in directory.

Parameters:
  • palettes_dir (str | None) – The directory from which the palettes will be searched for. Defaults to the value specified in config.DEFAULT_PALETTES_DIR.

  • search_builtins – Whether to also include built-in palettes such as ‘css’ or ‘basic’ in the search.

  • search_cwd – Whether to also search palettes in the current working directory.

  • kind – The kinds of palettes to include in the search. Can be either Palette, StackPalette, or a list of any of those.

colorir.palette.delete_palette(palette, palettes_dir=None)

Permanently deletes the file associated with a palette.

Be careful when using this function, there is no way to recover a palette after it has been deleted.

Parameters:
  • palette (str) – The name of the palette that will be deleted.

  • palettes_dir (str | None) – The directory containing the palette to be deleted. Defaults to the value specified in config.DEFAULT_PALETTES_DIR.