Every Python developer has been burned by terminal output at least once. A 40-line traceback scrolls past in monochrome and the interesting frame is gone before you can read it. You print() a nested dict and get a wall of characters with no visual hierarchy. You write a quick progress indicator, and on a colleague’s legacy Windows console it emits a stream of garbled box-drawing bytes instead of a bar. The standard library gives you sys.stdout and a pile of ANSI escape codes — and leaves everything else, from line wrapping to East-Asian character widths, entirely up to you.

Rich, maintained by Textualize, attacks exactly this gap. It is the library behind the colored tracebacks, tables, progress bars, and markdown rendering you see in a huge share of modern Python CLIs. Its promise is simple: describe what you want to show, and it figures out how to fit it into whatever rectangle of cells the terminal currently offers, whether that is an 80-column SSH session, a Jupyter cell, or a Windows console stuck in legacy mode.

The remarkable part is how small the core contract is. The whole system — 100 Python modules in the rich package, 67 test files under tests/ — reduces every widget to an immutable tuple called Segment, negotiated through a two-method protocol. This post walks the real source tree of Textualize/rich at main, mapping the actual render flow from Console.print() down to raw cells, with every line number taken from the code as it exists today.

Rich terminal rendering architecture: Console, protocol, markup, styles, segments, measurement and widgets

The overview map: Console as the hub, the duck-typed render protocol on its left, the markup and style layers feeding it, and every composite widget bottoming out in Segment atoms.

Reading the overview from left to right:

  • Console.render, L1288 — the hub method: casts the input, dispatches to __rich_console__, and flattens the result into Segments.
  • rich_cast, L18 — recursively unwraps objects exposing __rich__, with a visited-set loop guard and a gibberish-attribute sentinel to detect liar objects.
  • RE_TAGS, L12 — a single regex that defines the entire [bold red] markup grammar.
  • Style.parse, L498 — turns words like "bold red on blue" into a Style instance, with word parsing and caching.
  • Segment, L48 — the NamedTuple(text, style, control) atom every widget ultimately reduces to.
  • Measurement, L11 — the min/max cell-width contract negotiated before anything is drawn.
  • ratio_resolve, L14 — the Fraction-based loop that splits available width across columns and layout regions.
  • Progress, L1054 — progress bars built as a composition of interchangeable ProgressColumn widgets.
  • Traceback, L250 — the pretty-exception renderer that turns sys.excepthook output into syntax-highlighted frames.

The detail diagram below expands each of those boxes into the concrete classes and helper functions that implement them — including the one-module protocol layer, the theme stack, the cell-width table, and the box-drawing glyph registry.

Detailed Rich internals: Console methods, protocol helpers, markup tokenizer, Style and Theme stacks, Segment operations, Measurement math and widget classes

Detail view: from `Console._collect_renderables` through the protocol, grammar, styling, and width-math layers down to the final Segment stream.

The Console: one facade over every terminal quirk

rich/console.py is the largest module in the package at 2,301 lines, and Console (L575) is the class everyone actually touches. Its constructor accepts markup, highlight, emoji, theme, and legacy_windows options, and it sniffs the environment lazily — the module even exposes an _environ mapping (L611) so tests can fake os.environ. Everything enters through Console.print() (L1646), which first calls _collect_renderables (L1494) to flatten positional arguments plus sep, end, and padding into one ordered list. Each element is then pushed through render().

render() (L1288) is worth reading closely because it is where the type dispatch happens. It calls rich_cast first; if the object exposes __rich_console__, that method is invoked with the console and a ConsoleOptions object (L107) carrying max_width, height, justify, and overflow. Strings get converted by render_str into Text with markup applied. The two type aliases at the top of the flow — RenderableType (L261) and RenderResult (L265) — define the contract: a renderable is anything protocol-shaped, and a result is merely an iterable of more renderables or Segments. Around the core, Console offers capture() (L1090) to redirect output into a buffer for later export, set_alt_screen (L1195) for full-screen apps, and export_text/save_text (L2186/L2218) to dump recorded output back to disk.

Segments and the render protocol: everything bottoms out in one tuple

rich/protocol.py is only 31 lines long, yet the whole library hangs on it. is_renderable (L8) is a duck check for str, __rich__, or __rich_console__, and rich_cast (L18) keeps calling __rich__ until the object stops producing new ones. Two defensive details stand out. A rich_visited_set breaks type-level cycles so a pathological __rich__ cannot loop forever. And a _GIBBERISH sentinel string catches objects that claim to have every attribute — a real hazard when rendering arbitrary user objects — by checking whether they pretend to own an attribute nobody would define. If they do, Rich refuses to trust them and falls back to repr().

The destination of all this is Segment (L48), a NamedTuple of text, an optional style, and an optional tuple of control codes. Its cell_length property (L66) delegates width computation to cell_len() in rich/cells.py (L98), which uses a fast frozenset membership test (_is_single_cell_widths, L35) for ASCII and falls back to a Unicode width table for wide characters. Segment then offers the row-level surgery the rest of the library needs: adjust_line_length (L341) pads or crops a line to an exact width, set_shape (L413) does the same while preserving alignment, and divide (L617) crops segments into row or cross shapes — the operation that lets one renderable be clipped into a rectangular region without breaking it.

The markup grammar and the style system

Console markup — the [bold red] syntax everyone knows from Rich examples — is implemented in a 206-line module. RE_TAGS at L12 is the entire grammar: ((\\*)\[([a-z#/@][^[]*?)]). Tags must start with a lowercase letter, # (hex color), / (closing), or @ (link), which is why arbitrary [brackets] in your text pass through untouched. _parse (L73) walks the matches into (position, text, tag) triples, and render (L106) balances open and close tags into a stack, raising MarkupError (L167 onward) with the exact character position on mismatches. A companion escape() (L48) exists precisely because users embed user-provided strings, and it doubles trailing backslashes so they cannot invert a bracket.

Styles live in rich/style.py. Style (L40) is a frozen record of colors, attributes, links, and metadata; Style.parse (L498) interprets phrase words into it; NULL_STYLE (L762) is the identity element for the cheap + combination operator; and StyleStack (L765) resolves nested contexts. Style names, meanwhile, are resolved through Theme (L7 in theme.py), which seeds itself from DEFAULT_STYLES (L3 in default_styles.py) — a dict of 154 built-in entries spanning the file’s lines 3 through 170, including namespaces like markdown.*, repr.*, and logging.level.*. Themes can be loaded from INI-style config files via Theme.from_file (L38) and layered at runtime with ThemeStack (L81), which pushes and pops whole style dictionaries.

Measuring and dividing width: the math behind tables and layout

Before Rich draws anything, it asks how much space it wants. Measurement (L11 in measure.py) is a NamedTuple(min_width, max_width) with normalize (L24) and clamp (L59) helpers — the entire negotiation vocabulary. Widgets implement __rich_measure__ alongside __rich_console__, and the console consults both.

When several renderables must share one width, rich/_ratio.py earns its keep. ratio_resolve (L14) walks a list of edges carrying size, ratio, and minimum_size, computing a Fraction(remaining, sum_of_ratios) portion each pass; any edge whose share falls below its minimum gets pinned to that minimum, and the loop repeats until fixed-size and flexible edges reconcile. Companions ratio_reduce (L75) and ratio_distribute (L107) handle shrinking and distribution. This one 129-line module is what Table columns, Layout.split_row/split_column (L289/L297 in layout.py), and Columns all lean on — which is why Rich’s tables can honor explicit widths, ratios, and minimums simultaneously without any widget knowing about the others.

From wcwidth tables to Fraction ratios: build facts

Several engineering details in the tree deserve a closer look, because they explain behaviors users meet in production:

  • Two runtime dependencies, total. pyproject.toml (L26) declares exactly markdown-it-py>=2.2.0 and pygments>=2.13.0,<3.0.0 — markdown parsing and syntax highlighting — and requires Python >= 3.10 (L9). Everything else, including wcwidth emulation, is in-tree.
  • Legacy Windows is handled by substitution, not a second renderer. rich/box.py defines LEGACY_WINDOWS_SUBSTITUTIONS (L404), which swaps ROUNDED for SQUARE and friends when the console reports legacy mode — the same glyph tables simply remap.
  • Tracebacks survive truncated instructions. rich/traceback.py computes an instruction index from frame_summary.f_lasti // 2 (L532) to locate the precise expression being executed, and Traceback.__init__ floors max_frames at 4 when enabled (L338) so a bad user config cannot hide entire stacks.
  • Emoji is a data problem, not a logic problem: _emoji_codes.py is 3,610 lines holding 3,608 :shortcode: entries in one dict (L1), consumed via the _emoji_replace helper.
  • Live displays are timer-driven, not frame-driven: Live (L41 in live.py) runs a thread that waits exactly 1 / refresh_per_second seconds per redraw (L35), defaulting to 4 Hz — predictable CPU cost on slow SSH links.
  • Markdown rendering composes existing widgets rather than defining new output: CodeBlock.__rich_console__ builds a Syntax instance (L186 in markdown.py), and TableElement reuses Table directly (L250). In notebooks, JupyterMixin (L36 in jupyter.py) renders the same Segment stream into HTML via _repr_mimebundle_ (L41) and falls back to IPython.display (L89) — the same engine that powers traceback styling in IPython.
  • The package ships a py.typed marker, and its own quality bar is enforced by a pytest suite of 67 test files (dev dependency pytest>=7.0.0, pyproject L43).
  • On CPython, Rich’s cell_len mirrors the behavior of the interpreter’s own East-Asian width handling so that slicing text by cells never splits a wide character.

Honest Limits

Rich is not a TUI framework. Live and Layout can redraw regions in place, but interactive widgets — scrollable lists, focus management, input handling — belong to Textual; if you need event-driven UI, you will outgrow Rich quickly. Second, the render loop is inherently synchronous: render() walks the object tree and re-measures on every refresh, so a giant Tree redrawn at 4 Hz costs real CPU; there is no incremental diffing of unchanged regions. Third, markup and style strings are parsed at render time with regexes and phrase parsers — Style.parse results are cached, but deeply nested markup in a hot loop still pays tokenization costs. Fourth, some behavior is platform-sensitive: legacy Windows substitutions, terminal-size detection, and Jupyter integration all branch on the environment, so pixel-perfect parity across every terminal is not promised. Finally, while the core contract (Segment, the two-method protocol) is stable and beautifully small, many convenience modules — progress, table, traceback — churn between minor versions, and code that reaches into their internals should pin its dependency.

Watch PyShine on YouTube

Contents