Every developer eventually needs a real terminal interface: a dashboard that survives SSH, an installer with live logs, a REPL companion, a database browser. For years the honest options were curses (archaic API, zero layout engine) or hand-rolled ANSI escape codes that break on every terminal you did not test. Textual, from Textualize, took a different bet: build the entire web-development mental model — a DOM, CSS, async event handlers, testing tools — directly on top of characters in a terminal.

That ambition is exactly why reading its source is worth an afternoon. When your Textual app flickers, when a key binding silently refuses to fire, or when a reactive attribute changes but the screen does not repaint, the documentation will not save you. The answer is always in one of a handful of files: app.py orchestrates, message_pump.py delivers, widget.py renders, _compositor.py paints, and the css/ package decides what everything looks like.

This tour follows the main branch of Textualize/textual (version 8.2.8 at the time of writing). Every class, file and line number below was verified against the actual tree — no invented symbols. Two architecture diagrams anchor the walk: a compact overview of the runtime layers, then a detailed map of the classes and their hand-offs.

Textual overview architecture: App object, DOM tree, TCSS engine, compositor, message pump and testing harness

Overview of Textual's runtime layers: the App object drives a driver and a screen stack; every DOM node is a message pump; a per-screen compositor turns widgets into strips of styled characters; the TCSS engine resolves styles; the reactive system connects data changes to repaints.

Reading the overview from left to right:

  • App.run, L2308 — the synchronous entry point wraps run_async in asyncio.run and owns the whole lifecycle, from stylesheet loading to shutdown.
  • MessagePump._process_messages_loop, L634 — the single queue every widget, screen and the app itself drain messages from, merging superseded messages and injecting idle events.
  • Widget.render, L4432 — the one method users override; the private _render at L4460 promotes its return value into a cached Visual.
  • Widget.render_line, L4250 — rendering is per-row: each line becomes an immutable Strip served from a render cache.
  • Compositor.render_update, L1096 — decides between a full repaint and a partial update based on dirty regions, so typing in one input never repaints the whole screen.
  • Stylesheet.apply, L470 — matches parsed TCSS rules against each node and fills its Styles object with resolved declarations.
  • DOMQuery, L59 — the selector engine behind widget.query(...), reusing TCSS selector syntax for Python-side DOM queries.
  • Reactive._check_watchers, L377 — the reactive descriptor calls watch_* and compute_* methods by naming convention whenever an attribute changes.
  • Pilot.press, L76 — the headless test harness that posts real key events into the same message pump your production app uses.

The detail diagram goes one level deeper, into the individual classes:

Textual detail architecture: App.run, Driver, Screen and ModalScreen, DOMNode, Widget, Compositor, Strip, TCSS parse and tokenize, BindingsMap, reactive and Pilot

Detailed view: from App.run and the Driver, through the DOM tree and the compositor's strip painting, down to the TCSS tokenizer, the bindings map, the reactive descriptor machinery and Pilot-driven testing.

The App object is a message pump that owns screens

App is declared at app.py, L296 as class App(Generic[ReturnType], DOMNode) — a DOM node first, a UI second. The file is the largest in the package at roughly 5,000 lines, and it concentrates the lifecycle: run (L2308) normalizes the event loop, run_async (L2220) builds the driver and default screen, and _process_messages (L3364) hosts the main loop. An app_prelude coroutine inside it loads CSS_PATH files and pushes every inherited DEFAULT_CSS string into the stylesheet with add_source before the first frame is drawn.

Input and output are delegated to a Driver (driver.py, L17), an abstract class whose process_message (L77) funnels parsed terminal bytes into the app. Screens are a stack, not a router: push_screen (L2895), switch_screen (L3001) and pop_screen (L3096) manage it, and get_default_screen (L1380) instantiates the first one. Default key bindings live at app.py L454 — ctrl+q is a priority quit binding, and the ctrl+p command palette key is a class constant (COMMAND_PALETTE_BINDING, L441). There is even a hot-reload path: _on_css_change (L2364) rebuilds the stylesheet when files change, polled by a timer that set_interval(0.25) arms during startup (L3416).

From Python inheritance to a DOM tree

The DOM abstraction is refreshingly small. DOMNode (dom.py, L135) carries identity (id, classes, _css_type_names) and — critically — the default-CSS inheritance mechanism. _get_default_css (L713) walks the MRO collecting each base class’s DEFAULT_CSS string, recording a tie-breaker index and a scope (the class’s TCSS type name, unless SCOPED_CSS is disabled). Inheritance order therefore decides specificity: a widget subclass’s styles override Widget’s defaults, which themselves declare scrollbar sizing rules at widget.py, L290 — including scrollbar-size-vertical: 2.

Children are declared by overriding compose as a generator, with the compose helper (compose.py, L12) wrapping plain widgets; compose_add_child (dom.py L393) consumes it. The shipping widget library lives in src/textual/widgets/ — 58 modules — and the base case is instructive: Static (widgets/_static.py, L12) subclasses Widget with inherit_bindings=False, proving that even key bindings follow inheritance unless explicitly cut off.

From TCSS text to painted cells

Textual’s CSS dialect (“TCSS”) gets a full engine under src/textual/css/. Tokenizing is a small state machine: tokenize is an instance of TCSSTokenizerState (tokenize.py, L307) wrapping a character-level Tokenizer. Parsing then runs parse (parse.py, L452), which tokenizes the source, substitutes $variables via substitute_references (L368), and yields rule sets through parse_rule_set (L130) and parse_declarations (L295).

The Stylesheet class (stylesheet.py, L142) holds those rule sets. add_source (L333) accepts default CSS with tie-breakers so built-in styles rank below user styles; apply (L470) walks each node’s ancestors and classes to find matching rules and writes the result into that node’s Styles object (styles.py, L886). Units like 50% or 1fr resolve through Scalar values measured against the terminal size at layout time. The same selector syntax powers runtime queries: DOMQuery (query.py L59) raises NoMatches (L40) or TooManyMatches (L44) just like a real DOM API.

From reactive attributes to repaints

The reactive system is a descriptor, not a framework magic. Reactive (reactive.py, L125) is instantiated through the reactive factory (L437) or its quieter sibling var (L475), with flags for repaint, layout, recompose, bindings and even toggle_class. On first mount, _initialize_object (L231) wires each descriptor; on assignment, _set (L316) runs and _check_watchers (L377) invokes watch_<name> methods (L394) plus computed-value chains declared as compute_<name> (L254).

A concrete example from the widget base: virtual_size = Reactive(Size(0, 0), layout=True) at widget.py, L357 — scrolling a container marks layout as required, and the screen’s idle handler (_on_idle, screen.py, L1172) resumes the update timer that ends in _compositor_refresh (L1188). That chain — attribute assignment to watcher to dirty flag to compositor refresh — is the backbone of every Textual UI, and reading it once makes all widget behavior legible.

The compositor: painting only what changed

Each Screen constructs its own Compositor in __init__ (screen.py, L290), so screen switching is just choosing which compositor paints. The compositor’s full_map (L480) assigns screen-space regions to widgets using their layout classes; render_update (L1096) compares dirty regions against the full screen and picks a complete repaint or a partial Chop-based update; render_strips (L1185) then walks visible widgets, calling render_lines on each and clipping to the terminal grid. The unit of painting is the Strip (strip.py, L69) — an immutable list of styled segments for one row. Content produced by render is promoted by visualize (visual.py, L75) into a Visual (L123) that knows how to emit strips for any size. Geometry primitives (Offset L72, Size L192, Region L320 in geometry.py) keep the dirty-region bookkeeping cheap and allocation-light.

From widget count to binding fields: build facts

A few concrete numbers make the design’s scale tangible:

  • app.py is 5,041 lines and widget.py 4,957; dom.py is 1,945 and _compositor.py 1,273 — the complexity lives in two deliberate hot spots, orchestration and rendering.
  • The Binding dataclass (binding.py, L55) carries nine fields: key, action, description, show, key_display, priority, tooltip, id and system; BindingsMap (L185) merges BINDINGS classvars along the MRO, and Screen.BINDINGS (screen.py L268) defines tab/shift+tab focus cycling.
  • The message loop deduplicates in-flight work: pending messages can replace the current one when can_replace allows it (message_pump.py L650-660), and when the queue empties the pump injects an Idle event and flushes callbacks (L678-693).
  • The Key event (events.py, L261) derives its name property (L295) through key-alias normalization in keys.py (L205, L341), which is how ctrl+q becomes the on_key handler naming scheme.

Testing without a terminal

Because every node is a message pump, tests can run the real thing headlessly. App.run_test (app.py, L2133) returns a Pilot (pilot.py, L62) with press (L76), click (L192), hover (L349), pause (L535) and exit (L562), plus _wait_for_screen (L473) to let screens settle. No mocks are involved: the pilot posts genuine events into the genuine queue. The project’s own suite runs this under pytest with pytest-asyncio in auto mode and pytest-textual-snapshot for visual regression — the snapshot tests carry 448 exported SVG frames against which every pull request’s rendering is compared pixel by pixel. The codebase itself is type-checked with mypy and formatted with black, both pinned in pyproject.toml — worth mirroring if you build widgets on top of Textual’s APIs.

Honest Limits

This tour maps the core, not the whole surface. The widgets/ package (58 modules, from DataTable to the tree-sitter-powered TextArea) has its own conventions and deserves a separate walkthrough. Line numbers refer to main as of this writing and will drift — always re-check against the revision you pin. Performance characteristics are nuanced: the compositor’s partial updates are clever, but Python-level per-cell work means very high-frequency updates still need care (batching via with app.batch_update(), or the BLANK widget flag for huge scroll containers). Finally, the TCSS engine is not CSS: it supports a pragmatic subset, and anything exotic (floats, z-index layering across screens) is expressed differently than on the web. Terminal variance is quarantined in dedicated modules — the xterm input parser (_xterm_parser.py), Windows-specific timing (_win_sleep.py) and ANSI theme defaults (_ansi_theme.py) — but exotic terminal emulators can still surface quirks the test matrix never exercises. Read the source before fighting it — that is precisely what this tour is for.

Watch PyShine on YouTube

Contents