4. API - Styles

The colorzero library also includes a series of classes which act a bit like stylesheets for formatting large strings. Different classes are used to produce different types of output, such as HTMLStyles for HTML (and CSS) output, or TermStyles for ANSI terminal output.

4.1. Style Class

class colorzero.Style(fg, bg=<Color Default>)[source]

Represents a named “style” with a foreground (fg) and background (bg) Color (or Default).

If fg is an instance of Color it is accepted verbatim. Otherwise, a Color will be constructed with its value. Likewise for bg, which defaults to Default if not specified.

4.2. Stylesheets

Stylesheets are constructed with an initial mapping of names to suitable style values, or can be constructed with a set of keyword arguments which will be used to create the initial mapping:

>>> style = TermStyles({
... 'info': Style(Color('blue'), Default),
... 'warn': Style(Color('white'), Color('red')),
... })

The style values can either be a Style instance, or anything that could be used to construct a Style instance, including a Color instance, or valid arguments that could be used to construct a Color instance, or a tuple of two such values (representing the “fg” and “bg” components respectively). The value None can also be specified, which will be converted to a Style with Default as both foreground and background:

>>> style2 = TermStyles({
... 'info': 'blue',
... 'warn': ('white', 'red'),
... })
>>> style == style2

Style mappings are mutable (like an ordinary dict), but keys must be strings, and values will be converted in the same manner as during construction:

>>> style['error'] = 'red'
>>> style
TermStyles({'info': Style(fg=<Color html='#0000ff' rgb=(0, 0, 1)>,
bg=<Color Default>), 'warn': Style(fg=<Color html='#ffffff'
rgb=(1, 1, 1)>, bg=<Color html='#ff0000' rgb=(1, 0, 0)>), 'error':
Style(fg=<Color html='#ff0000' rgb=(1, 0, 0)>, bg=<Color Default>)})

Style mappings can be used with format strings to generate output in a variety of styles. The format spec for each template must be the name of an entry within the mapping. For example:

>>> from colorzero import *
>>> s = TermStyles(warn='red', reset=None)
>>> f'{s:warn}Warning{s:reset}: Do not push the button!'
'\x1b[1;31m\x1b[49mWarning\x1b[0m: Do not push the button!'

It is important to bear in mind that the formatting behaviour is stateful. In other words, as the styles are substituted into a string, the instance is keeping track of the current style. This permits descendants like HTMLStyles to determine when tags need closing or for TermStyles to determine when to reset foreground or background colors:

>>> s = HTMLStyles(warn='red', reset=None)
>>> print(f'{s:warn}This is red ')
<span class="warn">This is red
>>> print('and this will still be red ')
and this will still be red
>>> print(f'because the span has not closed yet{s:reset}')
because the span has not closed yet</span>

If the current foreground and background style is not Default once formatting is complete, you may need to call reset() before continuing to format the next string to ensure correct behaviour. The reset() method will return whatever string would be needed to reset the current style to the default (if any):

>>> print(f'{s:warn}This is red')
<span class="warn">This is red
>>> print(s.reset())

4.3. BaseStyles Class

class colorzero.BaseStyles(styles=None, **kwargs)[source]

Represents a mapping of (arbitrary) names to Style instances. This is an abstract base class; most users will be more interested in the concrete descendants: HTMLStyles or TermStyles which can be used with format strings to produce styled output.


Reset the “current” style to one with Default foreground and background.

This is useful when one stylesheet is repeatedly used to format strings, and you wish to guarantee that the style is reset before the next formatting operation. For example:

4.4. StripStyles Class

class colorzero.StripStyles(styles=None, **kwargs)[source]

A degenerate stylesheet class that always returns the empty string for all formatting operations, and the reset() method.

4.5. HTMLStyles Class

class colorzero.HTMLStyles(styles=None, *, tag='span', **kwargs)[source]

A stylesheet that outputs HTML elements when formatting strings.

The name of the elements produced is specified by the tag argument, which defaults to “span”. Style names must be valid CSS identifiers, or escapable to valid CSS identifiers (in practice, this means no spaces, and no empty strings). A ValueError will be raised if you attempt to assign such a key.

The stylesheet() method can be used to output a valid CSS stylesheet to be used with the generated HTML.


A generator method that yields rules of a CSS stylesheet for all defined styles. The prefix, if given, specifies anything that should be output before each rule such as any parent CSS selectors.

For example:

>>> from colorzero import *
>>> styles = HTMLStyles(warn='red', info='blue', reset=None)
>>> print('\n'.join(styles.stylesheet('div.body ')))
div.body span.warn { color: rgb(255, 0, 0); background-color: inherit; }
div.body span.info { color: rgb(0, 0, 255); background-color: inherit; }
div.body span.reset { color: inherit; background-color: inherit; }

4.6. TermStyles Class

class colorzero.TermStyles(styles=None, *, term_colors='8', **kwargs)[source]

A stylesheet that outputs ANSI escape codes.

The term_colors argument specifies the sorts of codes produced. This can be:

  • “8” - the default, indicating only the original 8 DOS colors (black, red, green, yellow, blue, magenta, cyan, and white) are supported. Technically, 16 foreground colors are supported via use of the “bold” style for “intense” colors, if the terminal supports this.

  • “256” - indicates the terminal supports 256 colors via 8-bit color ANSI codes

  • “16m” - indicating the terminal supports ~16 million colors via 24-bit color ANSI codes