This page is the complete API reference for the Style, Color, and Segment classes, along with their supporting types. These are the lowest-level building blocks in Rich's rendering pipeline.
Segment objects are produced during rendering, see Rendering Pipeline and Segments.Diagram: Module and class relationships
Sources: rich/style.py1-20 rich/color.py1-20 rich/segment.py1-32 rich/default_styles.py1-5
Style classDefined in rich/style.py36-755
A Style encodes all visual attributes that can be applied to terminal text: foreground color, background color, text decorations, a hyperlink URL, and arbitrary metadata. Instances are immutable and hashable; combination always produces a new object.
The type alias StyleType = Union[str, Style] (rich/style.py18) is used throughout Rich's API wherever a string style definition or a Style object is accepted.
All parameters are keyword-only. Boolean attributes accept True, False, or None (meaning "not set / inherit").
| Parameter | Type | Effect |
|---|---|---|
color | Color | str | None | Foreground text color |
bgcolor | Color | str | None | Background color |
bold | bool | None | Bold text |
dim | bool | None | Dim / faint text |
italic | bool | None | Italic text |
underline | bool | None | Single underline |
underline2 | bool | None | Double underline |
blink | bool | None | Slow blink |
blink2 | bool | None | Fast blink |
reverse | bool | None | Swap fore/background |
conceal | bool | None | Hidden / concealed |
strike | bool | None | Strikethrough |
frame | bool | None | Framed |
encircle | bool | None | Encircled |
overline | bool | None | Overline |
link | str | None | OSC 8 hyperlink URL |
meta | dict | None | Arbitrary metadata (serialized via pickle) |
Sources: rich/style.py127-201
Style.null() → Style
Returns the module-level NULL_STYLE singleton — a style with no attributes set. More efficient than Style() because no new object is created. rich/style.py203-206
Style.parse(style_definition: str) → Style
Parses a style definition string. Results are lru_cache-cached (maxsize 4096). Raises errors.StyleSyntaxError on invalid input. rich/style.py492-557
Style definition grammar:
style ::= token*
token ::= color_name
| "on" color_name
| attribute
| "not" attribute
| "link" url
| "none"
attribute ::= "bold" | "b" | "dim" | "d" | "italic" | "i" | "underline" | "u"
| "blink" | "blink2" | "reverse" | "r" | "conceal" | "c"
| "strike" | "s" | "underline2" | "uu" | "frame"
| "encircle" | "overline" | "o"
Style.normalize(style: str) → str
Parses and re-serializes a style string to a canonical form. Useful for equality comparison of style strings. rich/style.py383-398
Style.from_color(color=None, bgcolor=None) → Style
Creates a style with only color fields set (no attribute bitmask overhead). rich/style.py208-230
Style.from_meta(meta: dict) → Style
Creates a style carrying only metadata. rich/style.py232-251
Style.on(meta=None, **handlers) → Style
Creates a style with metadata. Keyword arguments are stored as @key entries (e.g. Style.on(click=handler) stores {"@click": handler}). rich/style.py253-269
Style.combine(styles: Iterable[Style]) → Style
Combines an iterable of styles left-to-right. rich/style.py596-607
Style.chain(*styles: Style) → Style
Combines positional style arguments left-to-right. rich/style.py609-620
Style.pick_first(*values: Optional[StyleType]) → StyleType
Returns the first non-None value from the arguments. Raises ValueError if all are None. rich/style.py400-406
Sources: rich/style.py203-620
| Property | Type | Description |
|---|---|---|
color | Optional[Color] | Foreground color, or None |
bgcolor | Optional[Color] | Background color, or None |
link | Optional[str] | Hyperlink URL, or None |
link_id | str | Unique ID string used in OSC 8 escape codes |
transparent_background | bool | True if bgcolor is None or the default color |
background_style | Style | A new Style with only the background color |
meta | Dict[str, Any] | Deserialized metadata dict (read-only) |
without_color | Style | Copy of this style with color and bgcolor set to None |
Boolean text attributes (bold, dim, italic, underline, blink, blink2, reverse, conceal, strike, underline2, frame, encircle, overline) are each descriptor properties returning True, False, or None. Implemented via the internal _Bit descriptor class. rich/style.py21-33 rich/style.py271-283
Sources: rich/style.py443-490
copy() → Style
Returns a copy of the style. Returns NULL_STYLE if the style is null. rich/style.py622-642
clear_meta_and_links() → Style
Returns a copy with link and meta stripped. Result is lru_cache-cached. rich/style.py644-665
update_link(link=None) → Style
Returns a copy with a different link URL. rich/style.py667-688
render(text="", *, color_system=ColorSystem.TRUECOLOR, legacy_windows=False) → str
Wraps text with the ANSI escape sequences for this style. Returns plain text if color_system is None or text is empty. Adds OSC 8 hyperlink sequences when link is set (unless legacy_windows=True). rich/style.py690-714
get_html_style(theme=None) → str
Returns a CSS rule string suitable for use in style="" attributes. Accepts an optional TerminalTheme for color translation. Result is lru_cache-cached. rich/style.py559-594
test(text=None) → None
Writes styled text directly to sys.stdout. For testing only. rich/style.py716-726
| Method | Behaviour |
|---|---|
__add__(other) | Combines two styles; the right-hand style overrides left where attributes are set |
__bool__() | False if the style has no colors, attributes, link, or meta |
__str__() | Regenerates the style definition string (e.g. "bold red on black") |
__eq__ / __ne__ | Identity by hash |
__hash__() | Hash over _color, _bgcolor, _attributes, _set_attributes, _link, _meta |
When combining two styles with +, the right-hand style wins for any attribute it explicitly sets. Attributes that are unset (None) in the right style are inherited from the left. rich/style.py729-755
Diagram: Style combination semantics
Sources: rich/style.py729-755
StyleStackDefined in rich/style.py761-792
A push-down stack of accumulated Style objects. Used internally during markup rendering (see Markup and Formatting).
| Member | Description |
|---|---|
__init__(default_style) | Initialize with a base style |
.current | Property — the style at the top of the stack |
.push(style) | Push current + style onto the stack |
.pop() | Pop the top style and return the new current |
NULL_STYLEModule-level sentinel defined at rich/style.py758 as Style(). All null-style paths return this singleton to avoid allocation.
DEFAULT_STYLESDefined in rich/default_styles.py5-171
A Dict[str, Style] mapping named style identifiers to Style instances. This is the default style theme used by Console. Categories include:
| Prefix | Examples |
|---|---|
| (none) | "bold", "italic", "underline", "reset", "dim" |
"repr." | "repr.number", "repr.str", "repr.url", "repr.bool_true" |
"logging." | "logging.level.info", "logging.keyword" |
"traceback." | "traceback.error", "traceback.title" |
"progress." | "progress.description", "progress.percentage" |
"json." | "json.key", "json.number", "json.str" |
"markdown." | "markdown.h1", "markdown.code_block" |
"bar." | "bar.back", "bar.complete", "bar.pulse" |
"inspect." | "inspect.attr", "inspect.callable" |
"table." | "table.header", "table.cell" |
"prompt." | "prompt.choices", "prompt.invalid" |
"iso8601." | "iso8601.date", "iso8601.time", "iso8601.timezone" |
Sources: rich/default_styles.py5-171
Color classDefined in rich/color.py302-568
Color is an immutable NamedTuple. It represents a single terminal color in one of four storage types, and knows how to emit ANSI escape code sequences and downgrade itself to a lesser color system.
| Field | Type | Description |
|---|---|---|
name | str | Human-readable name (the string passed to parse, or the hex value) |
type | ColorType | Storage type of this color |
number | Optional[int] | ANSI color number (0–255), or None for truecolor/default |
triplet | Optional[ColorTriplet] | RGB triplet, or None for non-truecolor |
ColorType enumDefined in rich/color.py36-44
| Value | Integer | Meaning |
|---|---|---|
DEFAULT | 0 | Terminal default color |
STANDARD | 1 | One of 16 named ANSI colors (0–15) |
EIGHT_BIT | 2 | 256-color palette (0–255) |
TRUECOLOR | 3 | 24-bit RGB |
WINDOWS | 4 | Windows legacy console colors |
ColorSystem enumDefined in rich/color.py22-33
| Value | Integer | Meaning |
|---|---|---|
STANDARD | 1 | 16-color ANSI |
EIGHT_BIT | 2 | 256-color |
TRUECOLOR | 3 | 24-bit RGB |
WINDOWS | 4 | Windows legacy |
ColorParseErrorRaised by Color.parse() when the input string does not match any recognized color format. rich/color.py288-289
Color.parse(color: str) → Color
Parses a color string. lru_cache-cached (maxsize 1024). Accepts: rich/color.py431-482
| Format | Example | Result type |
|---|---|---|
| Named ANSI color | "red", "bright_cyan" | STANDARD or EIGHT_BIT |
"default" | "default" | DEFAULT |
| 6-digit hex | "#ff0000" | TRUECOLOR |
color(N) | "color(200)" | STANDARD (N<16) or EIGHT_BIT |
rgb(r,g,b) | "rgb(255,0,128)" | TRUECOLOR |
Color.from_ansi(number: int) → Color
Creates a Color from an 8-bit ANSI number (0–255). rich/color.py380-394
Color.from_triplet(triplet: ColorTriplet) → Color
Creates a truecolor Color from a ColorTriplet. The name is set to the hex string. rich/color.py396-406
Color.from_rgb(red, green, blue) → Color
Creates a truecolor Color from three float components (0–255). rich/color.py408-420
Color.default() → Color
Returns a Color instance with type=ColorType.DEFAULT. rich/color.py422-429
| Property | Type | Description |
|---|---|---|
system | ColorSystem | Derives the ColorSystem for this color's type |
is_system_defined | bool | True if the actual RGB value is determined by terminal theme |
is_default | bool | True if type == ColorType.DEFAULT |
Sources: rich/color.py332-347
get_ansi_codes(foreground=True) → Tuple[str, ...]
Returns ANSI SGR parameter strings for this color. lru_cache-cached. rich/color.py484-510
| Color type | Foreground example | Background example |
|---|---|---|
| DEFAULT | ("39",) | ("49",) |
| STANDARD (0–7) | ("31",) for red | ("41",) |
| EIGHT_BIT | ("38", "5", "200") | ("48", "5", "200") |
| TRUECOLOR | ("38", "2", "255", "0", "0") | ("48", "2", "255", "0", "0") |
get_truecolor(theme=None, foreground=True) → ColorTriplet
Converts this color to a ColorTriplet using the provided TerminalTheme for theme-defined colors. rich/color.py349-378
downgrade(system: ColorSystem) → Color
Converts this color to a representation compatible with a lower ColorSystem. lru_cache-cached. rich/color.py512-568
Downgrade paths:
ANSI_COLOR_NAMESDefined in rich/color.py49-285
A dict mapping color name strings to their ANSI palette index (0–255). Both grey and gray spellings are included. The first 16 entries are the standard ANSI colors; the rest are the xterm-256 named colors.
parse_rgb_hex(hex_color: str) → ColorTriplet
Parses a 6-character hex string (without #) to a ColorTriplet. rich/color.py571-577
blend_rgb(color1, color2, cross_fade=0.5) → ColorTriplet
Linearly interpolates between two ColorTriplet values. Used by Style.get_html_style() for the dim effect. rich/color.py580-591
Sources: rich/color.py302-591
Segment classDefined in rich/segment.py64-699
Segment is a NamedTuple representing the atomic unit of output from the Rich rendering pipeline. It pairs a text string with an optional Style and an optional sequence of control codes.
| Field | Type | Description |
|---|---|---|
text | str | The text content |
style | Optional[Style] | Visual style to apply |
control | Optional[Sequence[ControlCode]] | Non-printable control sequences |
| Property | Type | Description |
|---|---|---|
cell_length | int | Number of terminal cells occupied by text (0 for control segments) |
is_control | bool | True if control is not None |
ControlType enumDefined in rich/segment.py35-53
| Name | Value |
|---|---|
BELL | 1 |
CARRIAGE_RETURN | 2 |
HOME | 3 |
CLEAR | 4 |
SHOW_CURSOR | 5 |
HIDE_CURSOR | 6 |
ENABLE_ALT_SCREEN | 7 |
DISABLE_ALT_SCREEN | 8 |
CURSOR_UP | 9 |
CURSOR_DOWN | 10 |
CURSOR_FORWARD | 11 |
CURSOR_BACKWARD | 12 |
CURSOR_MOVE_TO_COLUMN | 13 |
CURSOR_MOVE_TO | 14 |
ERASE_IN_LINE | 15 |
SET_WINDOW_TITLE | 16 |
ControlCode is a type alias for tuples of (ControlType,), (ControlType, int|str), or (ControlType, int, int). rich/segment.py56-60
Segment.line() → Segment
Returns Segment("\n"). rich/segment.py184-187
Segment.apply_style(segments, style=None, post_style=None) → Iterable[Segment]
Applies a base style and/or a post-style around each segment's existing style. The composition is style + segment.style + post_style. Does nothing for control segments. rich/segment.py189-228
Segment.filter_control(segments, is_control=False) → Iterable[Segment]
Filters segments by their is_control attribute. rich/segment.py230-247
Segment.split_lines(segments) → Iterable[List[Segment]]
Splits a flat sequence of segments on \n characters, yielding one list per line. rich/segment.py249-276
Segment.split_lines_terminator(segments) → Iterable[Tuple[List[Segment], bool]]
Like split_lines, but each yielded item is (line_segments, had_newline). rich/segment.py278-307
Segment.split_and_crop_lines(segments, length, style=None, pad=True, include_new_lines=True) → Iterable[List[Segment]]
Splits on \n and then crops or pads each line to exactly length cells. rich/segment.py309-354
Segment.adjust_line_length(line, length, style=None, pad=True) → List[Segment]
Pads a line to length (appending a space segment with style) or crops it by splitting the last overlapping segment. rich/segment.py356-399
Segment.get_line_length(line) → int
Returns the total cell width of a list of non-control segments. rich/segment.py401-412
Segment.get_shape(lines) → Tuple[int, int]
Returns (max_width, height) of a list of lines. rich/segment.py414-426
Segment.set_shape(lines, width, height=None, style=None, new_lines=False) → List[List[Segment]]
Crops/pads all lines to width and optionally extends to height rows with blank segments. rich/segment.py428-462
Segment.align_top / align_bottom / align_middle
Pad a list of lines to a target height by inserting blank rows at the bottom, top, or both sides respectively. rich/segment.py464-551
Segment.simplify(segments) → Iterable[Segment]
Merges adjacent segments that share the same Style into a single segment. rich/segment.py553-578
Segment.strip_links(segments) → Iterable[Segment]
Returns segments with link removed from each style. rich/segment.py580-595
Segment.strip_styles(segments) → Iterable[Segment]
Returns segments with style set to None. rich/segment.py597-608
Segment.remove_color(segments) → Iterable[Segment]
Returns segments with color information stripped from each style (preserves other attributes). rich/segment.py610-630
Segment.divide(segments, cuts) → Iterable[List[Segment]]
Divides a sequence of segments at a series of absolute cell positions, yielding one List[Segment] per cut. Handles double-width characters correctly. rich/segment.py632-699
split_cells(cut: int) → Tuple[Segment, Segment]
Splits a single Segment at a given cell column. When the cut falls in the middle of a double-width character, that character is replaced with two spaces to preserve width. rich/segment.py158-182
Sources: rich/segment.py64-699
Segments and SegmentLines renderablesSegments (rich/segment.py702-724) is a simple renderable that wraps an Iterable[Segment] so it can be passed directly to Console.print(). Accepts new_lines=True to insert Segment.line() after each segment.
SegmentLines (rich/segment.py727-750) wraps a list of segment lists (one per line) as a renderable. Accepts new_lines=True to append a newline segment to each line.
Diagram: From Style/Color to terminal output
Sources: rich/style.py340-381 rich/color.py484-511 rich/segment.py64-108
| Format | Example | ColorType | Notes |
|---|---|---|---|
| Named ANSI (0–7) | "red", "black" | STANDARD | 16 standard colors |
| Named ANSI (8–15) | "bright_red" | STANDARD | Bright variants |
| Named 256 | "deep_sky_blue1" | EIGHT_BIT | xterm palette names |
color(N) | "color(200)" | STANDARD or EIGHT_BIT | N in 0–255 |
| Hex | "#ff0000" | TRUECOLOR | 6-digit lowercase or uppercase |
| RGB function | "rgb(255,0,128)" | TRUECOLOR | Comma-separated integers |
"default" | "default" | DEFAULT | Terminal default color |
Sources: rich/color.py431-482
Refresh this wiki
This wiki was recently refreshed. Please wait 2 days to refresh again.