Skip to content

Latest commit

 

History

History
727 lines (618 loc) · 22.5 KB

api-reference.md

File metadata and controls

727 lines (618 loc) · 22.5 KB

Public API Reference

stui is a small Streamlit-inspired terminal UI library. It is not official Streamlit, is not affiliated with Streamlit, and is not a Streamlit compatibility layer.

This page documents the supported public surface exposed by:

import stui as st

Names not listed here should be treated as private implementation details, including runtime classes, Textual widgets, and element dataclasses under stui.runtime, stui.app, stui.widgets, and stui.elements.

Public Imports

These names are intentionally exported from stui.__all__. Stability labels are defined in API Stability.

API Classification Notes
__version__ v1-stable Package version string.
bar_chart v1-stable Compact terminal bar summary, not plotting-library parity.
button v1-stable Core input widget.
cache_data v1-stable Process-local mutation-isolated data cache, graduated in v2.3.0.
cache_resource v1-stable Process-local shared-resource cache, graduated in v2.3.0.
caption v1-stable Core text output.
checkbox v1-stable Core input widget.
code v1-stable Core text output.
columns v1-stable Count-only responsive terminal columns that stack on narrow terminals.
container v1-stable Terminal grouping primitive, not a full layout engine.
data_table post-v2 experimental Selectable terminal rows that return a source-row index; no editing or dataframe dependency.
dataframe v1-stable Static terminal display; editing and sorting are out of scope.
divider v1-stable Core visual separator.
error v1-stable Core status output.
exception v1-stable Core status output for exceptions.
expander v1-stable Keyboard-toggleable terminal grouping primitive.
form v1-stable Deferred submit behavior is part of the v1 contract.
form_submit_button v1-stable One-shot form submit button.
header v1-stable Core text output.
help post-v1 experimental Help formatting and the public name need more feedback.
info v1-stable Core status output.
json v1-stable Static terminal JSON display with string fallback.
line_chart v1-stable Compact terminal sparkline summary, not plotting-library parity.
markdown v1-stable Core text output.
metric v1-stable Compact terminal summary display.
multiselect post-v2 experimental Checkbox-style multi-option selection, new in v2.1.0.
number_input v1-stable Numeric input widget.
path_input post-v2 experimental Text-first local path selection and metadata validation; no upload or file-content reads.
progress v1-stable Clamped terminal progress display.
radio v1-stable Selection input widget.
rerun v1-stable Flow-control helper for explicit reruns.
selectbox v1-stable Selection input widget.
session_state v1-stable Core state mapping and attribute proxy.
slider v1-stable Core numeric input widget.
spinner post-v1 experimental Status grouping behavior may still tighten in v1.x.
stop v1-stable Flow-control helper that halts the current script pass.
subheader v1-stable Core text output.
status post-v1 experimental Status grouping behavior may still tighten in v1.x.
tabs post-v2 experimental Stateful terminal workspaces; all blocks execute and only the active pane mounts.
success v1-stable Core status output.
table v1-stable Static terminal table display.
text v1-stable Core text output.
text_area v1-stable Multiline text editor with Ctrl+Enter apply, graduated in v2.3.0.
text_input v1-stable Core input widget.
title v1-stable Core text output.
toast post-v2 experimental Transient terminal notification, new in v2.1.0.
toggle v1-stable On/off switch with checkbox semantics, graduated in v2.3.0.
warning v1-stable Core status output.
write v1-stable Core text/value output.

Text and Status

st.help is post-v1 experimental while the terminal formatting and public name settle. The other text helpers in this group are v1-stable.

st.title(body, *, key=None) -> None
st.header(body, *, key=None) -> None
st.subheader(body, *, key=None) -> None
st.text(body) -> None
st.caption(body) -> None
st.markdown(body) -> None
st.code(body, language=None) -> None
st.write(*args) -> None
st.help(obj_or_text) -> None
import stui as st

st.title("Release dashboard", key="page-title")
st.markdown("Track local jobs without opening a browser.")
st.write("active jobs =", 3)
st.success(body) -> None
st.info(body) -> None
st.warning(body) -> None
st.error(body) -> None
st.exception(exc) -> None
st.status(label, state="running", expanded=False)
st.spinner(text="Working...")

st.status and st.spinner are post-v1 experimental while status grouping behavior is tested in real terminal apps.

try:
    raise RuntimeError("model failed")
except RuntimeError as exc:
    st.exception(exc)

with st.status("Indexing", state="running", expanded=True):
    st.write("Reading local files")

with st.spinner("Waiting for job"):
    st.write("Polling once")

st.help(st.progress)

st.status accepts state="running", "complete", or "error". It returns a context-manager object, renders a terminal status block, and can capture child elements when used with with. Child elements are visible when expanded=True; the default collapsed block keeps children grouped but hides them from the visible TUI. st.spinner returns a simple static display/context primitive; it does not animate, run background work, or expose a mutable update object. st.help renders plain text directly or a simple signature and docstring for Python objects; it is not a pager or object browser.

Data Display

st.json(obj) -> None
st.table(data, *, max_rows=None, max_cols=None) -> None
st.dataframe(data, *, max_rows=None, max_cols=None) -> None
st.data_table(
    data,
    *,
    selection_mode=None,
    key=None,
    disabled=False,
    on_select=None,
    args=None,
    kwargs=None,
    max_rows=None,
    max_cols=None,
    height=None,
    show_index=False,
) -> int | None
st.metric(label, value, delta=None) -> None
st.progress(value, text=None) -> None
st.bar_chart(data, *, width=None, height=None) -> None
st.line_chart(data, *, width=None, height=None) -> None
st.divider() -> None

In v2.0.0, st.json, st.progress, st.table, st.dataframe, st.metric, st.bar_chart, and st.line_chart are v1-stable static display primitives. Tables support scalars, lists or tuples of scalars, lists or tuples of dicts, lists or tuples of lists/tuples, dicts of scalar values, dicts of lists/tuples, dataclass instances, namedtuple-like objects, simple objects with public attributes, and pandas-like objects with to_dict(orient="records") and columns attributes. Multiline table cells are normalized for terminal display. st.dataframe is an alias for static table display; it does not add editing, sorting, selection, or pandas as a required dependency. Use max_rows and max_cols to cap static output; hidden rows or columns are called out with visible +N rows or +N cols markers.

st.data_table is post-v2 experimental and uses Textual's first-party table for optional single-row selection. With selection_mode="single", it returns the selected source-row index or None; without selection it remains a focusable interactive view and returns None. max_rows and max_cols affect display only, never the source index contract. Arrow keys move the cursor, Enter or Space selects, and mouse row clicks select where terminal mouse input is available. See Interactive Data.

Charts are compact terminal summaries. st.bar_chart supports numeric scalars, lists or tuples of numbers, dicts of numbers, simple (label, value) pairs, simple lists of dicts, and dict-of-column shapes with a numeric value, score, count, total, or y column. st.line_chart supports numeric scalars, lists or tuples of numbers, dicts of numeric series, simple (label, value) pairs, simple lists of dicts, and dict-of-column shapes with numeric series. Non-finite values are ignored. Unsupported or all-invalid data renders No chart data. Chart width and height values, when provided, must be positive integers.

import stui as st

st.metric("accuracy", "91.2%", delta="+1.8")
st.progress(0.6, text="training")
st.table([
    {"run": "baseline", "latency_ms": 42},
    {"run": "quantized", "latency_ms": 24},
])
st.bar_chart({"baseline": 42, "quantized": 24})

Layout

st.container, st.expander, st.columns, st.form, and st.form_submit_button are v1-stable. They are terminal grouping primitives, not browser layout compatibility APIs.

st.tabs is a post-v2 experimental terminal workspace primitive.

st.container()
st.columns(count)
st.expander(label, expanded=False, *, key=None)
st.form(key)
st.form_submit_button(
    label="Submit",
    *,
    disabled=False,
    on_click=None,
    args=None,
    kwargs=None,
) -> bool
st.tabs(
    labels,
    *,
    key=None,
    default=0,
    on_change=None,
    args=None,
    kwargs=None,
)

Use layout helpers as context managers:

import stui as st

with st.container():
    st.header("Inputs")
    name = st.text_input("Name")

left, right = st.columns(2)
with left:
    st.metric("Queued", 4)
with right:
    st.metric("Failed", 0)

with st.expander("Advanced", expanded=False, key="advanced"):
    dry_run = st.checkbox("Dry run", value=True)

with st.form("job-form"):
    batch = st.number_input("Batch size", min_value=1, value=8)
    submitted = st.form_submit_button("Queue job")

if submitted:
    st.success(f"Queued {name} with batch size {batch}")

overview, logs = st.tabs(["Overview", "Logs"], key="workspace")
with overview:
    st.metric("Queued", 4)
with logs:
    st.code("ready")

st.columns(count) accepts a positive integer and returns that many context managers. Columns render side-by-side when each column has enough terminal width, then stack vertically on narrow terminals. It does not support browser grid behavior, custom gaps, width ratios, tabs, sidebars, or horizontal scrolling. See Layout Primitives for the current layout boundary.

Every tab block executes in script order, but only the active pane's element subtree is mounted and focusable. The active index persists through normal widget state, callbacks, forms, and reruns. Left and Right switch the focused tab; mouse activation is supported. Nested tabs are supported. See Tabs for the execution contract and limitations.

Widgets

All widget keys are strings or None. When key is omitted, stui generates a stable key from the widget type, label, and call position.

Widget callbacks run after the changed value is committed to st.session_state. Pass positional callback arguments with args=(...) and keyword callback arguments with kwargs={...}.

st.button(
    label,
    key=None,
    help=None,
    disabled=False,
    on_click=None,
    args=None,
    kwargs=None,
) -> bool
if st.button("Refresh", key="refresh", help="Run the local refresh step"):
    st.info("Refresh requested")
st.slider(
    label,
    min_value=0,
    max_value=100,
    value=None,
    step=1,
    *,
    key=None,
    help=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> int | float
threshold = st.slider(
    "Threshold",
    0.0,
    1.0,
    value=0.5,
    step=0.1,
    key="threshold",
)
st.text_input(
    label,
    value="",
    *,
    key=None,
    placeholder=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> str
name = st.text_input("Run name", value="baseline", placeholder="baseline")

st.path_input is post-v2 experimental. It accepts local path text and returns an absolute normalized string without opening or parsing the target.

st.path_input(
    label,
    value="",
    *,
    root=None,
    kind="any",
    must_exist=False,
    extensions=None,
    browse=True,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> str

Relative paths resolve from root, or from the app script directory when no root is supplied. ~ expands; environment variables do not. root is not a security sandbox, and the initial v2.3 implementation is text-first: the browse flag reserves the experimental call shape but does not open a tree overlay. See Path Input.

st.text_area is stable in v2.3.0. Enter inserts a newline; Ctrl+Enter applies the current value and reruns. Inside a form, the applied value remains pending until the form submit commits it to st.session_state.

st.text_area(
    label,
    value="",
    *,
    height=6,
    key=None,
    placeholder=None,
    disabled=False,
    max_chars=None,
    on_change=None,
    args=None,
    kwargs=None,
) -> str
notes = st.text_area(
    "Run notes",
    value="Compare the candidate\nwith the baseline.",
    height=6,
    max_chars=2000,
    key="run-notes",
)

height must be an integer of at least 3. max_chars, when supplied, must be a positive integer and is enforced while editing as well as when the value is read by the script. Cursor and scroll restoration across reruns are best effort. C0/C1 terminal controls in the value, label, or placeholder are stored and rendered as visible \\xNN escapes; newlines, tabs, and printable Unicode remain unchanged. Live insertions and pastes are neutralized at the editor boundary before Textual renders the next frame, not only after submission.

st.checkbox(
    label,
    value=False,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> bool
dry_run = st.checkbox("Dry run", value=True, key="dry-run")
st.number_input(
    label,
    min_value=None,
    max_value=None,
    value=0,
    step=1,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> int | float
batch_size = st.number_input("Batch size", min_value=1, max_value=128, value=16)
st.selectbox(
    label,
    options,
    index=0,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
)
model = st.selectbox("Model", ["tiny", "base", "large"], index=1)
st.radio(
    label,
    options,
    index=0,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
)
mode = st.radio("Mode", ["fast", "balanced", "careful"], index=1)

st.multiselect is post-v2 experimental. It renders a checkbox-style option list: arrow keys move the highlight, Space or Enter toggles the highlighted option. It returns the selected options as a tuple kept in options order, and stored selections that are no longer present in options are dropped on the next run. default accepts a single option or a list of options.

st.multiselect(
    label,
    options,
    default=None,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> tuple
datasets = st.multiselect("Datasets", ["train", "val", "test"], default=["train"])

st.toggle is stable in v2.3.0. It behaves exactly like st.checkbox but renders as an on/off switch.

st.toggle(
    label,
    value=False,
    *,
    key=None,
    disabled=False,
    on_change=None,
    args=None,
    kwargs=None,
) -> bool
verbose = st.toggle("Verbose logs", value=False, key="verbose")

Notifications

st.toast is post-v2 experimental. It queues a short transient notification that appears in the terminal after the current script run renders, then disappears on its own. Toasts are not part of the rendered element tree, so stui check does not count them as visible elements, and a run that fails with an error drops its queued toasts.

st.toast(body) -> None
if st.button("Save"):
    st.toast("Settings saved")

Caching

st.cache_data and st.cache_resource are stable process-local decorators in v2.3.0. They do not write to disk, use the network, start workers, or survive process exit.

st.cache_data(func=None, *, ttl=None, max_entries=None)
st.cache_resource(func=None, *, ttl=None, max_entries=None)
@st.cache_data
def load_defaults():
    return {"device": "cpu"}


@st.cache_data(ttl=60, max_entries=128)
def load_rows(path: str):
    ...


@st.cache_resource
def load_model():
    ...

Both decorators accept ttl=None or a positive finite number and max_entries=None or a positive integer. Equivalent positional/keyword calls share a key after signature binding, keyword ordering does not affect the key, and least-recently-used entries are evicted when a limit is set.

st.cache_data serializes supported return values and restores a fresh value for every hit, protecting the cached copy from caller mutation. st.cache_resource returns the same object identity until invalidated or cleared. Arguments to both decorators must be pickle-compatible. Exceptions and unsupported cache_data results are never cached.

load_rows.clear()         # one decorated function, across app scopes
st.cache_data.clear()     # every data entry in this process
st.cache_resource.clear() # every resource entry in this process

Cache keys are isolated by app script, function source identity/fingerprint, and normalized arguments. Source changes recreate decorated functions with a new fingerprint. In watch mode, any tracked source change also clears all data and resource entries for the affected app runtime before rerun. See Caching for the exact contract and limits.

Concurrent callers coordinate one fill per key. A cached function that recursively requests its own unfinished key raises a readable RuntimeError instead of waiting on itself. Decorators used outside an active stui runtime retain function-instance isolation in the process fallback registry. Script-defined decorators retain a weak decoration-time runtime for ordinary worker calls. An unowned, contextless worker call made while an app is active raises a readable error rather than being assigned to the wrong app.

Session State

st.session_state[key]
st.session_state[key] = value
del st.session_state[key]
key in st.session_state
st.session_state.get(key, default=None)
st.session_state.items()
st.session_state.keys()
st.session_state.values()
st.session_state.name
st.session_state.name = value
import stui as st

if "count" not in st.session_state:
    st.session_state.count = 0

if st.button("Increment"):
    st.session_state.count += 1

st.write("count =", st.session_state.count)

Flow Control

st.rerun() -> None
st.stop() -> None
if st.button("Reset"):
    st.session_state.count = 0
    st.rerun()

if "token" not in st.session_state:
    st.warning("Missing token")
    st.stop()

CLI Validation

stui check APP.py
stui check APP.py --json
stui check APP.py --strict
stui check APP.py --strict --repeat 2
stui inspect APP.py
stui inspect APP.py --json
stui inspect APP.py --strict --repeat 3
stui selftest
stui selftest --json
stui selftest --strict
stui selftest --strict --repeat 2

stui check runs a script through the stui runtime without launching the interactive TUI. It exits 0 when the app renders without runtime errors, 1 for script/runtime/API errors, and 2 for invalid script paths. The --json payload includes strict, warnings, summary.warning_count, summary.runs_requested, summary.runs_completed, summary.total_element_count, and a runs list with per-pass element, warning, and error counts. In --strict mode, authoring warnings such as a script that renders no visible elements fail the check while keeping error: null and status: "ok" for warning-only failures. Use --repeat N to run the script multiple times in one runtime and catch repeat-run state or recovery issues.

stui inspect uses the same runtime but returns versioned, count-only diagnostics for elements, widgets, keys, nesting, local modules, watched files, timings, and cache aggregates. It discards user stdout/stderr and never reports session values, cache arguments/results, rendered content, environment values, or file contents. See Inspect And Safe Commands.

stui selftest --strict is an installed-package/release gate. It validates package metadata, bundled demo resources, all init templates, all bundled examples, and doctor diagnostics without launching a full TUI. Use --repeat N to repeat generated-template and bundled-example checks.

v2.4 Stable Status

The signatures above are intentionally covered by tests in v2.4.0. The classification table marks each top-level API as v1-stable, post-v1 experimental, or post-v2 experimental; see API Stability for the full compatibility promise and post-v1 deprecation policy.

v2.4.0 keeps the v2 stable APIs and v2.3 workspace, local-path, selectable-data, and diagnostics APIs intact while adding fullscreen data exploration to existing experimental tables on top of the contract in v2 readiness. Any change to stable names should be treated as a compatibility event unless it fixes a correctness, terminal, or security issue and is documented in the changelog and release notes.

These APIs stay experimental in v2.4.0 and remain outside the v2 stable contract:

  • Help and status: st.help, st.status, and st.spinner formatting and grouping behavior (post-v1 experimental).
  • Remaining from v2.1.0: st.multiselect and st.toast (post-v2 experimental). st.toggle graduates in v2.3.0.
  • New in v2.3.0: st.tabs, st.path_input, and st.data_table (post-v2 experimental).

st.cache_data, st.cache_resource, st.text_area, and st.toggle graduate to the stable API in v2.3.0 after their focused state, form, callback, concurrency, cache-isolation, and terminal interaction suites passed.

APIs and feature areas explicitly deferred from the v1 stable surface are listed in API Stability. They include st.sidebar, st.file_uploader, st.components, st.empty, editable dataframes, plotting-library parity, custom column ratios/gaps, browser/server runtime, websocket, or port-forwarding runtime.