Skip to content

clabe.runnable

ActivityIndicator

ActivityIndicator(
    console: Console | None = None,
    *,
    enabled: bool | None = None,
)

Shared, thread-safe manager for a single live activity display.

Owns a single rich.progress.Progress instance into which any number of concurrent runnables register an "activity". Because a terminal can only host one live region at a time, every activity shares the same Progress so concurrent spinners render as separate rows (each with its own spinner and elapsed-time counter) instead of fighting over the terminal.

The display is reference-counted: it starts when the first activity is entered and stops (clearing itself) when the last activity exits. This works for both blocking synchronous code running on worker threads and asynchronous code driven by an event loop.

The indicator shares its Console with the logging handler so that log lines emitted while the display is live render cleanly above the spinners rather than corrupting them.

Attributes:

Name Type Description
enabled bool

Whether the display is active. Defaults to False on non-interactive consoles (e.g. when output is piped to a file or running in CI), making every activity a no-op.

Example
indicator = ActivityIndicator()
with indicator.activity("Running my-task"):
    do_blocking_work()

Initialize the activity indicator.

Parameters:

Name Type Description Default
console Console | None

Console to render on. Defaults to the shared console used by the logging handler so that logs and spinners coordinate.

None
enabled bool | None

Force the display on or off. When None (default), the display is enabled only when the console is an interactive terminal.

None
Source code in src/clabe/runnable/_activity.py
def __init__(self, console: Console | None = None, *, enabled: bool | None = None) -> None:
    """
    Initialize the activity indicator.

    Args:
        console: Console to render on. Defaults to the shared console used
            by the logging handler so that logs and spinners coordinate.
        enabled: Force the display on or off. When ``None`` (default), the
            display is enabled only when the console is an interactive
            terminal.
    """
    self._console = console or _default_console
    self._enabled = self._console.is_terminal if enabled is None else enabled
    self._lock = threading.RLock()
    self._progress: Progress | None = None
    self._active = 0
    self._sink: ActivitySink | None = None
    self._observers: list[ActivityObserver] = []

enabled property

enabled: bool

Whether the activity display is active.

set_sink

set_sink(sink: ActivitySink | None) -> None

Routes activities through sink (e.g. a TUI) instead of the console.

Parameters:

Name Type Description Default
sink ActivitySink | None

The sink to render activities, or None to restore the default console rendering.

required
Source code in src/clabe/runnable/_activity.py
def set_sink(self, sink: ActivitySink | None) -> None:
    """
    Routes activities through ``sink`` (e.g. a TUI) instead of the console.

    Args:
        sink: The sink to render activities, or ``None`` to restore the
            default console rendering.
    """
    with self._lock:
        self._sink = sink

observe

observe(observer: ActivityObserver) -> Callable[[], None]

Registers observer to be entered around every activity, in addition to rendering.

Parameters:

Name Type Description Default
observer ActivityObserver

Called with the activity description; returns a context manager.

required

Returns:

Type Description
Callable[[], None]

A function that unregisters the observer.

Source code in src/clabe/runnable/_activity.py
def observe(self, observer: ActivityObserver) -> Callable[[], None]:
    """
    Registers ``observer`` to be entered around every activity, in addition to rendering.

    Args:
        observer: Called with the activity description; returns a context manager.

    Returns:
        A function that unregisters the observer.
    """
    with self._lock:
        self._observers.append(observer)

    def remove() -> None:
        with self._lock:
            if observer in self._observers:
                self._observers.remove(observer)

    return remove

activity

activity(description: str) -> Generator[None, None, None]

Display a spinner with elapsed time for the duration of the block.

Safe to nest and to use concurrently from multiple threads or coroutines. Registered observers are entered around the block whether or not the display is enabled.

Parameters:

Name Type Description Default
description str

Text shown next to the spinner.

required
Source code in src/clabe/runnable/_activity.py
@contextlib.contextmanager
def activity(self, description: str) -> Generator[None, None, None]:
    """
    Display a spinner with elapsed time for the duration of the block.

    Safe to nest and to use concurrently from multiple threads or coroutines. Registered observers are
    entered around the block whether or not the display is enabled.

    Args:
        description: Text shown next to the spinner.
    """
    with self._lock:
        observers = list(self._observers)
    with contextlib.ExitStack() as stack:
        for observer in observers:
            stack.enter_context(observer(description))
        with self._render(description):
            yield

ActivitySink

Bases: Protocol

An alternative destination for activity displays.

When a sink is registered on an ActivityIndicator, activities are rendered through the sink instead of the rich console. This lets a live TUI own the terminal and show progress inside itself, rather than having a console-based spinner corrupt the TUI's display.

activity

activity(description: str) -> AbstractContextManager[None]

Display activity for the duration of the returned context manager.

Source code in src/clabe/runnable/_activity.py
def activity(self, description: str) -> contextlib.AbstractContextManager[None]:
    """Display activity for the duration of the returned context manager."""
    ...

RunnableSpec dataclass

RunnableSpec(
    name: str | None = None,
    notify: str | None = None,
    show_activity: bool | None = None,
    notify_start: bool | None = None,
    notify_success: bool | None = None,
    notify_fail: bool | None = None,
    log_level: int = INFO,
)

Notification behaviour for a single @runnable.

All flags default to None (inherit) so that call-site rewraps can override individual fields without clobbering the rest. The decorator fills unset flags with True before storing the spec on the wrapper.

merge

merge(other: RunnableSpec) -> RunnableSpec

Return a copy where other's non-None fields win.

Source code in src/clabe/runnable/_settings.py
def merge(self, other: "RunnableSpec") -> "RunnableSpec":
    """Return a copy where ``other``'s non-``None`` fields win."""
    return replace(self, **{k: v for k, v in vars(other).items() if v is not None})

get_activity_indicator

get_activity_indicator() -> ActivityIndicator

Return the process-wide shared ActivityIndicator.

Using a single shared indicator guarantees that concurrent runnables cooperate on one live display rather than each trying to start its own (which the terminal cannot support).

Returns:

Name Type Description
ActivityIndicator ActivityIndicator

The lazily-created shared indicator.

Source code in src/clabe/runnable/_activity.py
def get_activity_indicator() -> ActivityIndicator:
    """
    Return the process-wide shared `ActivityIndicator`.

    Using a single shared indicator guarantees that concurrent runnables
    cooperate on one live display rather than each trying to start its own
    (which the terminal cannot support).

    Returns:
        ActivityIndicator: The lazily-created shared indicator.
    """
    global _default_indicator
    with _default_indicator_lock:
        if _default_indicator is None:
            _default_indicator = ActivityIndicator()
        return _default_indicator

runnable

runnable(
    fn: F,
    *,
    name: str | None = ...,
    notify: str | None = ...,
    show_activity: bool | None = ...,
    notify_start: bool | None = ...,
    notify_success: bool | None = ...,
    notify_fail: bool | None = ...,
) -> F
runnable(
    fn: None = ...,
    *,
    name: str | None = ...,
    notify: str | None = ...,
    show_activity: bool | None = ...,
    notify_start: bool | None = ...,
    notify_success: bool | None = ...,
    notify_fail: bool | None = ...,
) -> Callable[[F], F]
runnable(
    fn: Callable[..., Any] | None = None,
    *,
    name: str | None = None,
    notify: str | None = None,
    show_activity: bool | None = None,
    notify_start: bool | None = None,
    notify_success: bool | None = None,
    notify_fail: bool | None = None,
) -> Any

Wrap a callable with the shared runnable lifecycle (logging, activity spinner, notifications, and an OpenTelemetry span).

Use it as a decorator at definition time (@runnable or @runnable(name=..., notify=...)) or to rewrap an existing callable at the call site (runnable(obj.method, notify_success=False)()). Rewrapping merges over the callable's existing spec rather than nesting, so it never double-reports.

By default all notifications are on (start, success, failure). Pass notify_start=False etc. to suppress individual ones.

Parameters:

Name Type Description Default
fn Callable[..., Any] | None

The callable to wrap. Omit to use runnable as a decorator factory.

None
name str | None

Display name. Derived from the instance class or function name when omitted.

None
notify str | None

Custom start message (shown instead of "<name>…").

None
show_activity bool | None

Show a spinner while running. Default True.

None
notify_start bool | None

Notify on start. Default True.

None
notify_success bool | None

Notify on success. Default True.

None
notify_fail bool | None

Notify on failure. Default True.

None
Source code in src/clabe/runnable/_core.py
def runnable(
    fn: Callable[..., Any] | None = None,
    *,
    name: str | None = None,
    notify: str | None = None,
    show_activity: bool | None = None,
    notify_start: bool | None = None,
    notify_success: bool | None = None,
    notify_fail: bool | None = None,
) -> Any:
    """Wrap a callable with the shared runnable lifecycle (logging, activity
    spinner, notifications, and an OpenTelemetry span).

    Use it as a decorator at definition time (``@runnable`` or
    ``@runnable(name=..., notify=...)``) or to rewrap an existing callable at
    the call site (``runnable(obj.method, notify_success=False)()``). Rewrapping
    merges over the callable's existing spec rather than nesting, so it never
    double-reports.

    By default all notifications are on (start, success, failure). Pass
    ``notify_start=False`` etc. to suppress individual ones.

    Args:
        fn: The callable to wrap. Omit to use ``runnable`` as a decorator factory.
        name: Display name. Derived from the instance class or function name when omitted.
        notify: Custom start message (shown instead of ``"<name>…"``).
        show_activity: Show a spinner while running. Default ``True``.
        notify_start: Notify on start. Default ``True``.
        notify_success: Notify on success. Default ``True``.
        notify_fail: Notify on failure. Default ``True``.
    """
    overrides = RunnableSpec(
        name=name,
        notify=notify,
        show_activity=show_activity,
        notify_start=notify_start,
        notify_success=notify_success,
        notify_fail=notify_fail,
    )

    def wrap(target):
        # Unwrap to the original function (idempotent rewrap) and merge specs.
        # Bound methods are rebound so the wrapped callable keeps its instance.
        host = target.__func__ if inspect.ismethod(target) else target
        original = getattr(host, "__runnable_original__", host)
        prior = getattr(host, "__runnable_spec__", RunnableSpec())
        wrapper = _make_wrapper(original, prior.merge(overrides))
        return wrapper.__get__(target.__self__) if inspect.ismethod(target) else wrapper

    return wrap(fn) if fn is not None else wrap

set_include_timing

set_include_timing(value: bool) -> None

Enable or disable elapsed-time suffixes on success notifications.

Source code in src/clabe/runnable/_settings.py
def set_include_timing(value: bool) -> None:
    """Enable or disable elapsed-time suffixes on success notifications."""
    global _include_timing
    _include_timing = value