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:
PaletteBaseClass 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
palettemodule.- Parameters:
color_format (ColorFormat) – Color format specifying how the colors of this
Paletteshould be stored. Defaults to the value specified inconfig.DEFAULT_COLOR_FORMAT.colors (Palette | Dict[str, ColorBase | str | tuple]) – Colors that will be stored in this 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
Paletteinstance.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
palettesparameter. By default this occurrence logs a warning, but this behaviour can be changed through thewarningsparameter.- Parameters:
palettes (str | List[str] | None) – List of palettes located in the location represented by
palettes_dirthat should be loaded by thisPaletteinstance. Additionally may include built-in palettes such as ‘css’ ifsearch_builtinsis set toTrue. By default, loads all palettes found in the specified directory.palettes_dir (str | None) – The directory from which the palettes specified in the
palettesparameter will be loaded. Defaults to the value specified inconfig.DEFAULT_PALETTES_DIR.search_builtins – Whether
palettesmay also include built-in palettes such as ‘css’ or ‘basic’.search_cwd – Whether
palettesmay also include palettes located in the current working directory.color_format (ColorFormat | None) – Color format specifying how the colors of this
Paletteshould be stored. Defaults to the value specified inconfig.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
Palettegiven 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')]
- get_names(color)
Finds all names of the provided color in this
Palette.Compares the provided
colorto every color thePalettecontains 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_classclass 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']
- get(index, default=None)
Finds a color given its index.
- Parameters:
index (str | int) – Name or integer index of the color to be retrieved.
default – What to return instead of the color if it is not found.
- add(index, 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:
index (str) – Name or integer index of the new color.
color (ColorBase | str | tuple) – The value of the color to be created. Can be an instance of any
color_classclass or, alternatively, a color-like object that resembles the color you want to add.
Examples
Adding a new blue color to the palette by name:
>>> palette = Palette() >>> palette.add("bestblue", "#4287f5") >>> palette.bestblue Hex('#4287f5') >>> palette[0] Hex('#4287f5')
- update(index, color)
Updates a color to a new value.
- Parameters:
index (str | int) – Name or integer 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_classclass 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')
Change it back by index:
>>> palette.update(0, "dd0000") >>> palette.myred Hex('#dd0000')
- remove(index)
Removes a color from the palette.
- Parameters:
index (str | int) – Name or integer index of the color to be removed.
Examples
>>> palette = Palette(red=RGB(1, 0, 0), blue=RGB(0, 0, 1)) >>> palette.remove(0) >>> palette.remove("blue") >>> palette.colors == [] True
- save(name, palettes_dir=None)
Saves the changes made to this
Paletteinstance.If this method is not called after modifications made by
Palette.add(),Palette.update()andPalette.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
nmost similar colors tocolorin 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 aPaletteifn!= 1.
- item in self
Returns
`Trueif the color is found in the palette andFalseotherwise.
- 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=<object object>)
- class colorir.palette.StackPalette(colors=None, color_format=None)
Bases:
PaletteBaseClass that handles anonymous indexed colors stored as a stack.
This class may be used as a replacement for
Palettewhen the name of the colors is irrelevant.Examples
>>> spalette = StackPalette(["ff0000", "00ff00", "0000ff"]) >>> spalette[0] Hex('#ff0000')
- Parameters:
color_format (ColorFormat) – Color format specifying how the colors of this
StackPaletteshould be stored. Defaults to the value specified inconfig.DEFAULT_COLOR_FORMAT.colors (Iterable[ColorBase | str | tuple]) – Colors that will be stored in this palette.
- 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
StackPaletteinstance.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_dirthat should be loaded by thisStackPaletteinstance. By default, loads all palettes found in the specified directory.palettes_dir (str | None) – The directory from which the palettes specified in the
palettesparameter will be loaded. Defaults to the value specified inconfig.DEFAULT_PALETTES_DIR.search_builtins – Whether
palettesmay also include built-in palettes such as ‘tab10’ or ‘dark2’.search_cwd – Whether
palettesmay also include palettes located in the current working directory.color_format (ColorFormat | None) – Color format specifying how the colors of this
Paletteshould be stored. Defaults to the value specified inconfig.DEFAULT_COLOR_FORMAT.
- classmethod new_complementary(n, color=None, color_format=None, color_system=<object object>)
Creates a new palette with
ncomplementary 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
StackPaletteshould be stored. Defaults to the value specified inconfig.DEFAULT_COLOR_FORMAT.color_system (Type[ColorPolarBase]) – Which polar color system to use. Supported values are HSV, HSL, HCLuv and HCLab.
- classmethod new_analogous(n, sections=12, start=0, color=None, color_format=None, color_system=<object object>)
Creates a new palette with
nanalogous 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
StackPaletteshould be stored. Defaults to the value specified inconfig.DEFAULT_COLOR_FORMAT.color_system (Type[ColorPolarBase]) – Which polar color system to use. Supported values are HSV, HSL, HCLuv and HCLab.
- self & other
Join two palettes sequentially.
Examples
>>> StackPalette(["ff0000"]) & StackPalette(["0000ff"]) StackPalette([#ff0000, #0000ff])
- resize(n, repeat=False, grad_class=<object object>, **kwargs)
- 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_classclass 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_classclass 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
StackPaletteinstance.If this method is not called after modifications made by
StackPalette.add(),StackPalette.update()andStackPalette.remove(), the modifications on the palette will not be permanent.Examples
Create a new
StackPaletteand save it to the current directory:>>> spalette = StackPalette(["ff0000", "00ff00", "0000ff"]) >>> spalette.save(name="elementary")
- to_palette(names=None)
Converts this stack palette into a
Palette.- Parameters:
names (List[str] | None) – Names that will be given to the colors in the same order they appear in this stack palette. If omitted, the colors will be numerated and named as ‘cx’, where x is its index.
- 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
nmost similar colors tocolorin 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 aStackPaletteifn!= 1.
- item in self
Returns
`Trueif the color is found in the palette andFalseotherwise.
- 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=<object object>)
- 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.