API Reference¶
Components (shiny_kit.component)¶
Core OOP PyShiny lifecycle (Component, SubComponentProxy, subcomponent, Tab, ParentTab, BaseHeroTab).
Classes:
-
BaseHeroTab–Reusable glassmorphic Hero & Workflow landing
Tabcomponent. -
Component–Base class for OOP-driven Shiny modules with integrated UI, Server, Subcomponents, and Resource Gating.
-
HeroConfig–Configuration contract for a
BaseHeroTablanding view. -
HeroStatSpec–Static specification for a metric tile in the
.sv-stat-striphero strip. -
HomeTabEvents–Read-only reactive event streams emitted by
BaseHeroTab.server(). -
ParentTab–Container tab hosting child
Tabmodules inside a card navigation panel. -
SubComponentProxy–Class-level proxy returned when accessing a
subcomponentdescriptor on a Component class. -
Tab–Specialized
Componentrepresenting a navigable tab in a tabbed layout. -
WorkflowStepSpec–Static specification for a pillar/workflow card below the Hero section.
-
subcomponent–Descriptor declaring a child
Componentauto-mounted and auto-bound by its parentComponent.
BaseHeroTab
¶
BaseHeroTab(
*, config: HeroConfig | None = None, color_mode: Callable[[], str] | None = None
)
flowchart TD
shiny_kit.component.BaseHeroTab[BaseHeroTab]
shiny_kit.component.Tab[Tab]
shiny_kit.component.Component[Component]
shiny_kit.component.Tab --> shiny_kit.component.BaseHeroTab
shiny_kit.component.Component --> shiny_kit.component.Tab
click shiny_kit.component.BaseHeroTab href "" "shiny_kit.component.BaseHeroTab"
click shiny_kit.component.Tab href "" "shiny_kit.component.Tab"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Reusable glassmorphic Hero & Workflow landing Tab component.
Renders a two-column .sv-hero banner with gradient headline, primary/secondary CTA buttons,
an interactive live preview widget card, .sv-stat-strip metric tiles, and .sv-pillar-card
pipeline cards below the fold.
Methods:
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
render_preview_controls_ui–Optional header controls rendered on the right side of the live preview card.
-
render_preview_widget_ui–Renders the output widget container inside the glassmorphic preview card.
-
server–Binds server logic for the Hero tab and returns
HomeTabEventsstreams. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
title–Derives title from the class docstring without inheriting parent docstrings.
-
ui–Wraps the component UI in a Shiny
NavPanel. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Attributes:
-
has_session(bool) –Whether this component is currently bound to an active Shiny session.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
render_preview_controls_ui
classmethod
¶
render_preview_widget_ui
classmethod
¶
Renders the output widget container inside the glassmorphic preview card.
Source code in src/shiny_kit/component.py
server
¶
server(
id_: str, *, color_mode: Callable[[], str] | None = None, **_: Any
) -> HomeTabEvents
Binds server logic for the Hero tab and returns HomeTabEvents streams.
Source code in src/shiny_kit/component.py
sync_version
¶
title
classmethod
¶
title() -> str
Derives title from the class docstring without inheriting parent docstrings.
ui
classmethod
¶
Wraps the component UI in a Shiny NavPanel.
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
Component
¶
Base class for OOP-driven Shiny modules with integrated UI, Server, Subcomponents, and Resource Gating.
Subclasses can bind a typed BaseSessionState subclass via PEP 695 type parameter S and state_cls,
compose child Components via subcomponent(...), and declare pipeline prerequisites via requires.
Attributes:
-
state_cls(type[S]) –Concrete
BaseSessionStateassociated with this component. -
requires(ClassVar[tuple[Requirement, ...]]) –Declarative prerequisite rules gating the component.
-
module_id(str) –Shiny module namespace ID assigned when
server(id_)is bound.
Examples:
from shiny import render, ui
from shiny_kit.component import Component
from shiny_kit.decorators import bind_output
from shiny_kit.state import BaseSessionState
class AppState(BaseSessionState):
pass
class CounterCard(Component[AppState]):
@classmethod
def _render_ui(cls):
return ui.card(ui.output_text("label"))
@bind_output(render.text)
def label(self) -> str:
return f"Theme: {self.state.color_mode}"
Methods:
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
ui–Constructs and namespaces the UI tree for this component, adding a resource-gate container if
requiresis set. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
ui
classmethod
¶
Constructs and namespaces the UI tree for this component, adding a resource-gate container if requires is set.
Source code in src/shiny_kit/component.py
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
HeroConfig
dataclass
¶
HeroConfig(
badge_text: str,
headline: str,
subtitle: str,
primary_cta_label: str,
secondary_cta_label: str,
preview_title: str,
workflow_steps: tuple[WorkflowStepSpec, ...],
stats: tuple[HeroStatSpec, ...] = (),
pipeline_heading: str = "Workflow Pipeline",
pipeline_subtitle: str = "Explore each stage of the workflow below.",
)
Configuration contract for a BaseHeroTab landing view.
Attributes:
-
badge_text(str) –Eyebrow pill text displayed above the headline.
-
headline(str) –Main gradient headline text.
-
subtitle(str) –Lead paragraph text beneath the headline.
-
primary_cta_label(str) –Label for the primary action button.
-
secondary_cta_label(str) –Label for the secondary demo-loading button.
-
preview_title(str) –Header title of the glassmorphic live preview card.
-
workflow_steps(tuple[WorkflowStepSpec, ...]) –Sequence of workflow cards rendered below the fold.
-
stats(tuple[HeroStatSpec, ...]) –Sequence of metrics rendered in the
.sv-stat-stripbar.
HeroStatSpec
dataclass
¶
HomeTabEvents
dataclass
¶
Read-only reactive event streams emitted by BaseHeroTab.server().
Attributes:
-
launch_clicked(Callable[[], int]) –Reactive getter returning the click count of the primary launch button.
-
demo_clicked(Callable[[], int]) –Reactive getter returning the click count of the demo cohort button.
ParentTab
¶
flowchart TD
shiny_kit.component.ParentTab[ParentTab]
shiny_kit.component.Tab[Tab]
shiny_kit.component.Component[Component]
shiny_kit.component.Tab --> shiny_kit.component.ParentTab
shiny_kit.component.Component --> shiny_kit.component.Tab
click shiny_kit.component.ParentTab href "" "shiny_kit.component.ParentTab"
click shiny_kit.component.Tab href "" "shiny_kit.component.Tab"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Container tab hosting child Tab modules inside a card navigation panel.
Attributes:
Methods:
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
title–Derives title from the class docstring without inheriting parent docstrings.
-
ui–Wraps the component UI in a Shiny
NavPanel. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
title
classmethod
¶
title() -> str
Derives title from the class docstring without inheriting parent docstrings.
ui
classmethod
¶
Wraps the component UI in a Shiny NavPanel.
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
SubComponentProxy
¶
Tab
¶
flowchart TD
shiny_kit.component.Tab[Tab]
shiny_kit.component.Component[Component]
shiny_kit.component.Component --> shiny_kit.component.Tab
click shiny_kit.component.Tab href "" "shiny_kit.component.Tab"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Specialized Component representing a navigable tab in a tabbed layout.
Extracts its display title from the first line of the subclass's docstring via title()
and wraps super().ui(id_) inside a shiny.ui.nav_panel.
Attributes:
-
icon(HTML | None) –Optional Lucide SVG icon rendered in the tab header.
Methods:
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
title–Derives title from the class docstring without inheriting parent docstrings.
-
ui–Wraps the component UI in a Shiny
NavPanel. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
title
classmethod
¶
title() -> str
Derives title from the class docstring without inheriting parent docstrings.
ui
classmethod
¶
Wraps the component UI in a Shiny NavPanel.
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
WorkflowStepSpec
dataclass
¶
WorkflowStepSpec(
step_label: str,
description: str,
icon: str = "sparkles",
badge: str = "",
metrics: tuple[str, ...] = (),
target_tab: str | None = None,
)
Static specification for a pillar/workflow card below the Hero section.
Attributes:
-
step_label(str) –Card heading for the pipeline step.
-
description(str) –Body copy describing the step's capabilities.
-
icon(str) –Lucide icon name rendered in the card header. Defaults to
"sparkles". -
badge(str) –Optional uppercase pill badge text rendered at the top-right of the card.
-
metrics(tuple[str, ...]) –Optional metric pills displayed inside the card footer.
-
target_tab(str | None) –Optional target navbar tab ID associated with the step.
subcomponent
¶
Decorators (shiny_kit.decorators)¶
Reactive descriptors and class-based server binding decorators (BaseBinder, bind_*).
Classes:
-
BaseBinder–Abstract base descriptor and decorator for binding
Componentmethods to a PyShiny server session. -
BoundTask–Per-instance handle to a PyShiny
ExtendedTaskbound via@bind_task. -
bind_datagrid–Descriptor & decorator binding a method returning a tabular object to
shiny.render.DataGrid. -
bind_download–Descriptor & decorator binding a method yielding or returning bytes to
@render.download_button. -
bind_effect–Descriptor & decorator binding a
Componentmethod (sync or async) to a guarded reactive effect. -
bind_output–Descriptor & decorator binding a
Componentmethod (sync or async) to a Shiny renderer. -
bind_task–Descriptor & decorator wrapping a method into a non-blocking PyShiny
ExtendedTask. -
bind_widget–Descriptor & decorator binding a method returning an interactive widget/chart to
shinywidgets. -
reactive_calc–Descriptor wrapping a method into a per-instance, session-isolated
reactive.calc. -
reactive_prop–Descriptor wrapping a PyShiny
reactive.valuewith defaults and static type inference.
BaseBinder
¶
flowchart TD
shiny_kit.decorators.BaseBinder[BaseBinder]
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Abstract base descriptor and decorator for binding Component methods to a PyShiny server session.
All bind_* decorators (bind_output, bind_datagrid, bind_download, bind_effect, bind_task,
and custom domain binders) inherit from BaseBinder and implement bind(...), allowing
Component.server() to discover and bind them uniformly without hardcoded per-type loops.
Attributes:
-
fn(Callable[..., Any] | None) –Underlying component method decorated by this binder.
-
name(str) –Attribute name on the owning
Componentclass.
Methods:
-
bind–Binds this descriptor's method onto the active PyShiny module server session.
Source code in src/shiny_kit/decorators.py
bind
abstractmethod
¶
Binds this descriptor's method onto the active PyShiny module server session.
Source code in src/shiny_kit/decorators.py
BoundTask
¶
BoundTask(task: ExtendedTask[Any, R])
Per-instance handle to a PyShiny ExtendedTask bound via @bind_task.
Attributes:
-
task(ExtendedTask[Any, R]) –Underlying PyShiny
ExtendedTask. -
invocation_count(int) –Monotonically increasing count of task invocations.
-
warnings(tuple[str, ...]) –User-facing warnings captured during the latest run.
-
last_error(BaseException | None) –Exception raised by the latest failed run, if any.
Methods:
-
cancel–Cancels an in-flight background execution.
-
invoke–Invokes the background task with the given arguments.
-
result–Reactively retrieves the completed task result (raises silent cancel while running).
-
status–Reactively returns the current execution status of the task.
Source code in src/shiny_kit/decorators.py
bind_datagrid
¶
bind_datagrid(
id_: str | None = None,
*,
id_attr: str | None = None,
selection_mode: Literal["none", "row", "rows"] = "none",
filters: bool = True,
height: str | int | None = None,
height_attr: str | None = None,
width: str | int = "100%",
)
flowchart TD
shiny_kit.decorators.bind_datagrid[bind_datagrid]
shiny_kit.decorators.bind_output[bind_output]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.bind_output --> shiny_kit.decorators.bind_datagrid
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_output
click shiny_kit.decorators.bind_datagrid href "" "shiny_kit.decorators.bind_datagrid"
click shiny_kit.decorators.bind_output href "" "shiny_kit.decorators.bind_output"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator binding a method returning a tabular object to shiny.render.DataGrid.
Attributes:
-
selection_mode(Literal['none', 'row', 'rows']) –Row selection mode.
-
filters(bool) –Whether to enable per-column filter headers in the DataGrid.
-
height(str | int | None) –Optional CSS height string or pixel integer.
-
height_attr(str | None) –Optional attribute name on the component resolving the DataGrid height.
-
width(str | int) –CSS width string or pixel integer. Defaults to
"100%".
Methods:
-
bind–Wraps the bound method with
requiresgating and registers it onoutput. -
client_dimensions–Reads
(width, height)in pixels fromsession.clientdatafor the resolved output ID. -
resolve_target_id–Resolves the Shiny output ID from
component.<id_attr>,self.id_, orself.name. -
transform–Wraps non-null tabular values into
shiny.render.DataGrid.
Source code in src/shiny_kit/decorators.py
bind
¶
Wraps the bound method with requires gating and registers it on output.
Source code in src/shiny_kit/decorators.py
client_dimensions
¶
Reads (width, height) in pixels from session.clientdata for the resolved output ID.
Source code in src/shiny_kit/decorators.py
resolve_target_id
¶
Resolves the Shiny output ID from component.<id_attr>, self.id_, or self.name.
Source code in src/shiny_kit/decorators.py
transform
¶
Wraps non-null tabular values into shiny.render.DataGrid.
Source code in src/shiny_kit/decorators.py
bind_download
¶
flowchart TD
shiny_kit.decorators.bind_download[bind_download]
shiny_kit.decorators.bind_output[bind_output]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.bind_output --> shiny_kit.decorators.bind_download
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_output
click shiny_kit.decorators.bind_download href "" "shiny_kit.decorators.bind_download"
click shiny_kit.decorators.bind_output href "" "shiny_kit.decorators.bind_output"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator binding a method yielding or returning bytes to @render.download_button.
Attributes:
-
id_(str | None) –Optional explicit download button output ID.
-
filename(str | Callable[[Any], str]) –Static filename string or callable
(self) -> str.
Methods:
-
bind–Wraps the download generator with
requiresgating and registers it onoutput. -
client_dimensions–Reads
(width, height)in pixels fromsession.clientdatafor the resolved output ID. -
resolve_target_id–Resolves the Shiny output ID from
component.<id_attr>,self.id_, orself.name. -
transform–Hook for subclasses to transform the method's return value before passing it to the renderer.
Source code in src/shiny_kit/decorators.py
bind
¶
Wraps the download generator with requires gating and registers it on output.
Source code in src/shiny_kit/decorators.py
client_dimensions
¶
Reads (width, height) in pixels from session.clientdata for the resolved output ID.
Source code in src/shiny_kit/decorators.py
resolve_target_id
¶
Resolves the Shiny output ID from component.<id_attr>, self.id_, or self.name.
Source code in src/shiny_kit/decorators.py
transform
¶
Hook for subclasses to transform the method's return value before passing it to the renderer.
bind_effect
¶
flowchart TD
shiny_kit.decorators.bind_effect[bind_effect]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_effect
click shiny_kit.decorators.bind_effect href "" "shiny_kit.decorators.bind_effect"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator binding a Component method (sync or async) to a guarded reactive effect.
Attributes:
-
event_ids(tuple[str, ...]) –Input IDs triggering the effect via
reactive.event. -
notify_error(bool) –Whether uncaught non-silent exceptions are displayed as error toasts.
-
notify_warning(bool) –Whether captured user-facing warnings are displayed as warning toasts.
Methods:
-
bind–Wraps the effect method with
WarningCatcherand error handling and registersreactive.effect.
Source code in src/shiny_kit/decorators.py
bind
¶
Wraps the effect method with WarningCatcher and error handling and registers reactive.effect.
Source code in src/shiny_kit/decorators.py
bind_output
¶
flowchart TD
shiny_kit.decorators.bind_output[bind_output]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_output
click shiny_kit.decorators.bind_output href "" "shiny_kit.decorators.bind_output"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator binding a Component method (sync or async) to a Shiny renderer.
Subclasses (such as bind_datagrid or bind_altair) can set a default renderer_factory
and override transform(self, component, value) to post-process the method's return value
without writing manual sync/async wrapper boilerplate.
Attributes:
-
renderer_factory(Any) –Shiny renderer decorator/factory (e.g.
render.ui,render.text). -
id_(str | None) –Optional explicit output ID. Defaults to the decorated method's name.
Methods:
-
bind–Wraps the bound method with
requiresgating and registers it onoutput. -
client_dimensions–Reads
(width, height)in pixels fromsession.clientdatafor the resolved output ID. -
resolve_target_id–Resolves the Shiny output ID from
component.<id_attr>,self.id_, orself.name. -
transform–Hook for subclasses to transform the method's return value before passing it to the renderer.
Source code in src/shiny_kit/decorators.py
bind
¶
Wraps the bound method with requires gating and registers it on output.
Source code in src/shiny_kit/decorators.py
client_dimensions
¶
Reads (width, height) in pixels from session.clientdata for the resolved output ID.
Source code in src/shiny_kit/decorators.py
resolve_target_id
¶
Resolves the Shiny output ID from component.<id_attr>, self.id_, or self.name.
Source code in src/shiny_kit/decorators.py
transform
¶
Hook for subclasses to transform the method's return value before passing it to the renderer.
bind_task
¶
bind_task(
button_id: str | None = None,
*,
register_to: str | None = None,
on_success: Callable[[Any, Any], str | None] | str | None = None,
notify_success: str | Callable[[Any], str] | bool = True,
notify_warning: bool = True,
notify_error: bool = True,
progress_message: str | None = None,
**register_kwargs: Any,
)
flowchart TD
shiny_kit.decorators.bind_task[bind_task]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_task
click shiny_kit.decorators.bind_task href "" "shiny_kit.decorators.bind_task"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator wrapping a method into a non-blocking PyShiny ExtendedTask.
Synchronous methods are automatically offloaded to a background worker thread via
asyncio.to_thread so heavy workloads never block the main asyncio event loop.
Supports declarative register_to artifact registration, on_success callbacks,
automatic LazyShinyProgress reporting, and toast notifications upon completion.
Methods:
-
bind–Binds action-button triggers, busy-state synchronization, and completion handlers for the task.
Attributes:
-
display_label(str) –Human-readable label for progress bars and error notifications.
Source code in src/shiny_kit/decorators.py
display_label
property
¶
display_label: str
Human-readable label for progress bars and error notifications.
bind
¶
Binds action-button triggers, busy-state synchronization, and completion handlers for the task.
Source code in src/shiny_kit/decorators.py
bind_widget
¶
bind_widget(
id_: str | None = None,
*,
id_attr: str | None = None,
renderer_factory: Any = None,
autosize: bool = True,
resizer: Callable[[Any, float | None, float | None], Any] | None = None,
)
flowchart TD
shiny_kit.decorators.bind_widget[bind_widget]
shiny_kit.decorators.bind_output[bind_output]
shiny_kit.decorators.BaseBinder[BaseBinder]
shiny_kit.decorators.bind_output --> shiny_kit.decorators.bind_widget
shiny_kit.decorators.BaseBinder --> shiny_kit.decorators.bind_output
click shiny_kit.decorators.bind_widget href "" "shiny_kit.decorators.bind_widget"
click shiny_kit.decorators.bind_output href "" "shiny_kit.decorators.bind_output"
click shiny_kit.decorators.BaseBinder href "" "shiny_kit.decorators.BaseBinder"
Descriptor & decorator binding a method returning an interactive widget/chart to shinywidgets.
Lazily imports shinywidgets (defaulting to shinywidgets.render_altair or render_widget)
and optionally adapts the returned widget to its client container dimensions via a pluggable
resizer callback (widget, width, height) -> widget (or component.resizer).
Attributes:
-
autosize(bool) –Whether to resize the returned widget using
client_dimensions(component). -
resizer(Callable[[Any, float | None, float | None], Any] | None) –Optional resizer callback.
Methods:
-
client_dimensions–Reads
(width, height)in pixels fromsession.clientdatafor the resolved output ID. -
resolve_target_id–Resolves the Shiny output ID from
component.<id_attr>,self.id_, orself.name. -
transform–Resizes the returned widget to fit the active client container dimensions when
autosize=True.
Source code in src/shiny_kit/decorators.py
client_dimensions
¶
Reads (width, height) in pixels from session.clientdata for the resolved output ID.
Source code in src/shiny_kit/decorators.py
resolve_target_id
¶
Resolves the Shiny output ID from component.<id_attr>, self.id_, or self.name.
Source code in src/shiny_kit/decorators.py
transform
¶
Resizes the returned widget to fit the active client container dimensions when autosize=True.
Source code in src/shiny_kit/decorators.py
reactive_calc
¶
Descriptor wrapping a method into a per-instance, session-isolated reactive.calc.
Supports synchronous and asynchronous functions as well as optional input event filtering.
Attributes:
-
fn(Callable[..., Any] | None) –Underlying method wrapped by the descriptor.
-
events(tuple[str, ...]) –Optional input IDs to trigger reactive recalculation via
reactive.event. -
name(str) –Attribute name on the owning class.
Source code in src/shiny_kit/decorators.py
reactive_prop
¶
Descriptor wrapping a PyShiny reactive.value with defaults and static type inference.
Attributes:
-
default(T | None) –Default value stored in the per-instance
reactive.value. -
name(str) –Internal instance dictionary key storing the
reactive.Value.
Examples:
from shiny_kit.decorators import reactive_prop
from shiny_kit.state import BaseSessionState
class AppState(BaseSessionState):
selected_year: reactive_prop[int] = reactive_prop(2024)
Source code in src/shiny_kit/decorators.py
Session State & Artifacts (shiny_kit.state)¶
Session state (BaseSessionState) and reactive artifact registries (ArtifactRegistry, artifact_registry, Requirement).
Classes:
-
ArtifactRegistry–Reactive, session-isolated store for named pipeline artifacts.
-
BaseSessionState–Abstract session state base class holding reactive
artifact_registrystores, theme state, and cache. -
Requirement–Declarative prerequisite rule gating a
TaborComponentonBaseSessionStateresources. -
artifact_registry–Class-level descriptor declaring an
ArtifactRegistry[T]on aBaseSessionStatesubclass.
ArtifactRegistry
¶
ArtifactRegistry(
label: str,
*,
icon: str | None = None,
badge_class: str = "bg-primary",
show_in_navbar: bool = True,
namer: Callable[[T], str] | None = None,
toast: Callable[[T], str] | str | None = None,
on_register: Callable[..., None] | str | None = None,
on_select: Callable[..., None] | str | None = None,
on_remove: Callable[..., None] | str | None = None,
owner_state: BaseSessionState | None = None,
)
Reactive, session-isolated store for named pipeline artifacts.
Tracks a dictionary of named artifacts alongside an active selection key and a version counter, triggering PyShiny reactive invalidation automatically whenever artifacts are added, removed, or re-selected.
Methods:
-
clear–Removes all artifacts from the registry.
-
format_toast–Formats a completion toast message for
itemusing the registry'stoastspecification. -
get–Reactively looks up a specific artifact by name.
-
register–Registers or updates a named artifact and triggers reactive dependents and
on_registerhooks. -
remove–Removes a named artifact from the registry and updates the active selection if needed.
-
resolve_name–Resolves the registry key for
itemusingexplicit_name,self._namer, or common attributes. -
select–Sets the active artifact by name and invokes
on_selecthooks.
Attributes:
-
active(T | None) –Reactively returns the currently active artifact instance (or
Noneif empty). -
active_key(str | None) –Reactively returns the name of the currently active artifact.
-
count(int) –Reactively returns the number of registered artifacts.
-
items(dict[str, T]) –Reactively returns the mapping of registered artifact names to instances.
-
names(list[str]) –Reactively returns the ordered list of registered artifact names.
-
version(int) –Reactively returns the mutation counter for this registry.
Source code in src/shiny_kit/state.py
active
property
¶
Reactively returns the currently active artifact instance (or None if empty).
active_key
property
writable
¶
active_key: str | None
Reactively returns the name of the currently active artifact.
items
property
¶
Reactively returns the mapping of registered artifact names to instances.
clear
¶
Removes all artifacts from the registry.
format_toast
¶
format_toast(item: T) -> str
Formats a completion toast message for item using the registry's toast specification.
Source code in src/shiny_kit/state.py
register
¶
Registers or updates a named artifact and triggers reactive dependents and on_register hooks.
Source code in src/shiny_kit/state.py
remove
¶
Removes a named artifact from the registry and updates the active selection if needed.
Source code in src/shiny_kit/state.py
resolve_name
¶
Resolves the registry key for item using explicit_name, self._namer, or common attributes.
Source code in src/shiny_kit/state.py
select
¶
Sets the active artifact by name and invokes on_select hooks.
Source code in src/shiny_kit/state.py
BaseSessionState
¶
flowchart TD
shiny_kit.state.BaseSessionState[BaseSessionState]
click shiny_kit.state.BaseSessionState href "" "shiny_kit.state.BaseSessionState"
Abstract session state base class holding reactive artifact_registry stores, theme state, and cache.
Subclasses declare domain registries as class-level artifact_registry[T](...) attributes.
Ties state instances to session.id and auto-cleans via PyShiny's lifecycle hooks.
Attributes:
-
color_mode(Literal['light', 'dark']) –Reactive UI color theme mode.
-
user_id(str | None) –Optional authenticated user identifier.
-
preferences(dict[str, str]) –Arbitrary per-session user preferences dictionary.
-
root_session(Session | None) –Root Shiny
Sessionowning this state instance. -
navset_id(str) –Top-level navbar DOM ID used by
navigate_to(). -
cache(BaseCache) –Two-tier
BaseCacheshared across the application.
Examples:
from shiny_kit.state import BaseSessionState, artifact_registry
class MySessionState(BaseSessionState):
tables = artifact_registry[object]("Tables", icon="table")
state = MySessionState()
assert state.tables.count == 0
Methods:
-
bind_navbar–Binds top-level navbar dark-mode synchronization and reactive registry status badges.
-
format_task_success–Formats a default completion toast message for a task result
res. -
from_session–Retrieves or initializes typed state for the given session.
-
get_registry–Retrieves a named
ArtifactRegistryattribute on this state instance. -
navbar_controls–Returns
(nav_spacer(), nav_control(output_ui(badges_id)), nav_control(input_dark_mode(...)))items. -
navigate_to–Switches the active navigation panel in the root session.
-
on_reset–Optional hook called by
reset_all()when clearing session state. -
register_artifact–Registers
iteminto the namedArtifactRegistry, triggering itsnamerandon_registerhooks. -
render_navbar_badges–Renders reactive status badges for all declared registries with
show_in_navbar=True. -
reset_all–Clears all declared
ArtifactRegistrystores and callson_reset(). -
summary_counts–Reactively returns
{registry_name: count}across all declared registries.
Source code in src/shiny_kit/state.py
registries
property
¶
registries: dict[str, ArtifactRegistry[Any]]
Returns the ordered mapping of declared registry names to bound ArtifactRegistry instances.
bind_navbar
¶
bind_navbar(
input: Inputs,
output: Outputs,
*,
color_mode_id: str = "color_mode",
badges_id: str = "navbar_registry_badges",
) -> None
Binds top-level navbar dark-mode synchronization and reactive registry status badges.
Source code in src/shiny_kit/state.py
format_task_success
¶
Formats a default completion toast message for a task result res.
Source code in src/shiny_kit/state.py
from_session
classmethod
¶
from_session(session: Session | None = None) -> Self
Retrieves or initializes typed state for the given session.
Source code in src/shiny_kit/state.py
get_registry
¶
get_registry(name: str) -> ArtifactRegistry[Any]
Retrieves a named ArtifactRegistry attribute on this state instance.
Source code in src/shiny_kit/state.py
navbar_controls
classmethod
¶
navbar_controls(
*,
color_mode_id: str = "color_mode",
badges_id: str = "navbar_registry_badges",
default_mode: Literal["light", "dark"] = "light",
) -> tuple[Any, ...]
Returns (nav_spacer(), nav_control(output_ui(badges_id)), nav_control(input_dark_mode(...))) items.
Source code in src/shiny_kit/state.py
navigate_to
¶
Switches the active navigation panel in the root session.
Source code in src/shiny_kit/state.py
on_reset
¶
register_artifact
¶
register_artifact(
registry_name: str, item: Any, *, name: str | None = None, **kwargs: Any
) -> Any
Registers item into the named ArtifactRegistry, triggering its namer and on_register hooks.
Source code in src/shiny_kit/state.py
render_navbar_badges
¶
Renders reactive status badges for all declared registries with show_in_navbar=True.
Source code in src/shiny_kit/state.py
reset_all
¶
summary_counts
¶
Reactively returns {registry_name: count} across all declared registries.
Requirement
dataclass
¶
Declarative prerequisite rule gating a Tab or Component on BaseSessionState resources.
Parameters:
-
(registry¶str) –Name of the
ArtifactRegistryattribute onBaseSessionState. -
(min_count¶int, default:1) –Minimum number of registered items required to unlock the view.
-
(label¶str, default:'') –Human-readable description of the required resource.
-
(target_tab¶str | None, default:None) –Optional tab
id_to jump to when the user clicks the unlock action button.
Methods:
-
is_met–Reactively checks whether this requirement is satisfied in
state. -
status_text–Returns a formatted progress string (e.g. 'Formulations: 1 / 2 available').
is_met
¶
is_met(state: BaseSessionState) -> bool
status_text
¶
status_text(state: BaseSessionState) -> str
Returns a formatted progress string (e.g. 'Formulations: 1 / 2 available').
artifact_registry
¶
artifact_registry(
label: str = "",
*,
icon: str | None = None,
badge_class: str = "bg-primary",
show_in_navbar: bool = True,
namer: Callable[[T], str] | None = None,
toast: Callable[[T], str] | str | None = None,
on_register: Callable[..., None] | str | None = None,
on_select: Callable[..., None] | str | None = None,
on_remove: Callable[..., None] | str | None = None,
)
Class-level descriptor declaring an ArtifactRegistry[T] on a BaseSessionState subclass.
Source code in src/shiny_kit/state.py
Explorers (shiny_kit.explorers)¶
High-level domain explorer components (ArtifactSwitcher, TableExplorer, BasePlotterExplorer, WidgetPlotterExplorer).
Classes:
-
ArtifactSwitcher–Reusable selector, summary badge bar, deletion control, and file I/O component for an
ArtifactRegistry. -
BasePlotterExplorer–Generic interactive plotter explorer with
WidgetSelector-introspected controls. -
TableExplorer–Generic multi-view DataFrame and CSV export explorer.
-
WidgetPlotterExplorer–Interactive widget plotter explorer with
PlotterWidgetSelectorcontrols and container auto-sizing.
ArtifactSwitcher
¶
flowchart TD
shiny_kit.explorers.ArtifactSwitcher[ArtifactSwitcher]
shiny_kit.component.Component[Component]
shiny_kit.component.Component --> shiny_kit.explorers.ArtifactSwitcher
click shiny_kit.explorers.ArtifactSwitcher href "" "shiny_kit.explorers.ArtifactSwitcher"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Reusable selector, summary badge bar, deletion control, and file I/O component for an ArtifactRegistry.
Attributes:
-
registry_kind(ClassVar[str]) –Name of the
ArtifactRegistryattribute onself.state. -
label(ClassVar[str]) –Display label for the artifact selector dropdown.
-
show_count_in_label(ClassVar[bool]) –Whether to append
(count)to the selector label. -
enable_delete(ClassVar[bool]) –Whether to render a delete button for the active artifact.
-
enable_clear(ClassVar[bool]) –Whether to render a
"Clear All"button. -
enable_download(ClassVar[bool]) –Whether to render an artifact download button.
-
enable_upload(ClassVar[bool]) –Whether to render an artifact file upload control.
-
file_extension(ClassVar[str]) –Default file extension appended to downloaded artifacts.
-
upload_accept(ClassVar[Sequence[str]]) –Accepted file extensions for the upload control.
-
download_button_label(ClassVar[str]) –Label for the download button.
-
upload_label(ClassVar[str]) –Heading label above the file upload input.
-
upload_placeholder(ClassVar[str]) –Placeholder text inside the file upload input.
Methods:
-
active_for_download–Returns the artifact instance to serialize when downloading (defaults to
self.registry.active). -
choice_label–Formats the dropdown label for
item. -
download_filename–Returns a sanitized filename with
self.file_extensionfor the active artifact. -
empty_ui–Rendered when the registry has 0 items.
-
extra_buttons_ui–Optional extra action buttons placed alongside the Save/Delete controls.
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
load_artifact_from_path–Override when
enable_upload = Trueto deserialize an uploaded artifact file. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
serialize_artifact–Serializes
iteminto bytes for download. Defaults to callingitem.save()if defined. -
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
summary_ui–Optional status/badge block rendered below the dropdown.
-
sync_version–Updates the recorded version for
keywithout reporting a change. -
ui–Constructs and namespaces the UI tree for this component, adding a resource-gate container if
requiresis set. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
registry
property
¶
registry: ArtifactRegistry[T]
Returns the target ArtifactRegistry on self.state.
active_for_download
¶
Returns the artifact instance to serialize when downloading (defaults to self.registry.active).
choice_label
¶
download_filename
¶
download_filename(item: T | None) -> str
Returns a sanitized filename with self.file_extension for the active artifact.
Source code in src/shiny_kit/explorers.py
empty_ui
¶
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
load_artifact_from_path
¶
Override when enable_upload = True to deserialize an uploaded artifact file.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
serialize_artifact
¶
serialize_artifact(item: T) -> bytes | None
Serializes item into bytes for download. Defaults to calling item.save() if defined.
Source code in src/shiny_kit/explorers.py
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
summary_ui
¶
sync_version
¶
ui
classmethod
¶
Constructs and namespaces the UI tree for this component, adding a resource-gate container if requires is set.
Source code in src/shiny_kit/component.py
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
BasePlotterExplorer
¶
flowchart TD
shiny_kit.explorers.BasePlotterExplorer[BasePlotterExplorer]
shiny_kit.component.Component[Component]
shiny_kit.component.Component --> shiny_kit.explorers.BasePlotterExplorer
click shiny_kit.explorers.BasePlotterExplorer href "" "shiny_kit.explorers.BasePlotterExplorer"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Generic interactive plotter explorer with WidgetSelector-introspected controls.
Subclasses bind a plotter_registry mapping plot keys to (label, plotter_cls) pairs,
configure widget_selector_cls, implement active_subject(), and bind a chart output
renderer (such as WidgetPlotterExplorer).
Attributes:
-
plotter_registry(ClassVar[Mapping[str, tuple[str, type[Any]]]]) –Mapping of
{plot_key: (label, plotter_cls)}. -
widget_selector_cls(ClassVar[type[WidgetSelector]]) –WidgetSelectorsubclass used to introspect plotters. -
default_plot_key(ClassVar[str]) –Default selected plot key when available.
-
param_prefix(ClassVar[str]) –Input ID prefix for introspected plotter widgets.
-
sidebar_width(ClassVar[int]) –Width of the plot controls sidebar in pixels.
-
chart_height(ClassVar[str]) –CSS height of the chart output widget.
-
chart_output_id(ClassVar[str]) –Output ID of the main chart widget. Defaults to
"main_chart".
Methods:
-
active_subject–Returns the active domain model to plot, or None if unavailable.
-
available_choices–Returns
{plot_key: label}choices available forsubject. -
build_chart–Invokes
plotter.plot(subject)(override for plotters requiring special arguments). -
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
render_chart_widget–Override in subclasses to render the output container widget for
self.chart_output_id. -
render_extra_controls–Optional plot-specific controls rendered between Plot Type and Plot Parameters.
-
resolve_selected_plot–Selects the active plot key given
choicesand the previouscurrent_plot. -
resolved_plot_key–Resolves the currently selected valid plot key for
subject. -
selector_header_ui–Optional status or unlock hint badge rendered above the Plot Type dropdown.
-
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
ui–Constructs and namespaces the UI tree for this component, adding a resource-gate container if
requiresis set. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/explorers.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
active_subject
¶
available_choices
¶
Returns {plot_key: label} choices available for subject.
build_chart
¶
Invokes plotter.plot(subject) (override for plotters requiring special arguments).
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
render_chart_widget
¶
Override in subclasses to render the output container widget for self.chart_output_id.
render_extra_controls
¶
render_extra_controls(subject: M, plot_key: str) -> TagChild
Optional plot-specific controls rendered between Plot Type and Plot Parameters.
resolve_selected_plot
¶
resolve_selected_plot(
subject: M, choices: dict[str, str], current_plot: str | None
) -> str | None
Selects the active plot key given choices and the previous current_plot.
Source code in src/shiny_kit/explorers.py
resolved_plot_key
¶
resolved_plot_key(subject: M) -> str | None
Resolves the currently selected valid plot key for subject.
Source code in src/shiny_kit/explorers.py
selector_header_ui
¶
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
ui
classmethod
¶
Constructs and namespaces the UI tree for this component, adding a resource-gate container if requires is set.
Source code in src/shiny_kit/component.py
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
TableExplorer
¶
flowchart TD
shiny_kit.explorers.TableExplorer[TableExplorer]
shiny_kit.component.Component[Component]
shiny_kit.component.Component --> shiny_kit.explorers.TableExplorer
click shiny_kit.explorers.TableExplorer href "" "shiny_kit.explorers.TableExplorer"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Generic multi-view DataFrame and CSV export explorer.
Subclasses implement active_subject(), table_views(subject), and resolve_table(subject, mode)
to provide a reactive radio-button view switcher, optional status badges, a filterable
render.DataGrid, and one-click CSV export.
Attributes:
-
empty_icon(ClassVar[str]) –Lucide icon name shown when
active_subject()isNone. -
empty_title(ClassVar[str]) –Empty-state heading shown when
active_subject()isNone. -
empty_message(ClassVar[str]) –Empty-state description shown when
active_subject()isNone. -
csv_prefix(ClassVar[str]) –Filename prefix for exported
.csvfiles. -
grid_height(ClassVar[str]) –CSS height of the rendered DataGrid.
Methods:
-
active_subject–Returns the active domain object backing the table views (or None if unavailable).
-
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
resolve_selected_mode–Selects the active radio button mode given
choicesand the previouscurrent_mode. -
resolve_table–Returns the tabular object for
subjectandmode. -
serialize_csv–Serializes
dfto UTF-8 CSV bytes. Supports Polars (write_csv) and Pandas (to_csv) out of the box. -
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
table_views–Returns
{view_key: label}choices available forsubject. -
toolbar_badges_ui–Optional status badges displayed on the left of the table toolbar.
-
ui–Constructs and namespaces the UI tree for this component, adding a resource-gate container if
requiresis set. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
active_subject
¶
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
resolve_selected_mode
¶
Selects the active radio button mode given choices and the previous current_mode.
Source code in src/shiny_kit/explorers.py
resolve_table
¶
serialize_csv
¶
Serializes df to UTF-8 CSV bytes. Supports Polars (write_csv) and Pandas (to_csv) out of the box.
Source code in src/shiny_kit/explorers.py
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
table_views
¶
ui
classmethod
¶
Constructs and namespaces the UI tree for this component, adding a resource-gate container if requires is set.
Source code in src/shiny_kit/component.py
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
WidgetPlotterExplorer
¶
flowchart TD
shiny_kit.explorers.WidgetPlotterExplorer[WidgetPlotterExplorer]
shiny_kit.explorers.BasePlotterExplorer[BasePlotterExplorer]
shiny_kit.component.Component[Component]
shiny_kit.explorers.BasePlotterExplorer --> shiny_kit.explorers.WidgetPlotterExplorer
shiny_kit.component.Component --> shiny_kit.explorers.BasePlotterExplorer
click shiny_kit.explorers.WidgetPlotterExplorer href "" "shiny_kit.explorers.WidgetPlotterExplorer"
click shiny_kit.explorers.BasePlotterExplorer href "" "shiny_kit.explorers.BasePlotterExplorer"
click shiny_kit.component.Component href "" "shiny_kit.component.Component"
Interactive widget plotter explorer with PlotterWidgetSelector controls and container auto-sizing.
Lazily uses shinywidgets.output_widget and bind_widget so shiny-kit remains free of
charting library dependencies while providing a ready-to-use base class for Altair/Plotly/widget
plotter explorers.
Methods:
-
active_subject–Returns the active domain model to plot, or None if unavailable.
-
available_choices–Returns
{plot_key: label}choices available forsubject. -
build_chart–Invokes
plotter.plot(subject)(override for plotters requiring special arguments). -
has_changed–Tracks
versionunderkeyand returnsTruewhenversiondiffers from the previously recorded value. -
is_unlocked–Reactively checks whether all declarative
requiresrules are satisfied. -
notify–Displays a toast notification if running inside an active Shiny session.
-
notify_error–Formats and displays an error toast notification in the active Shiny session.
-
notify_warning–Displays a warning toast notification in the active Shiny session.
-
render_chart_widget–Renders the
shinywidgets.output_widgetcontainer forself.chart_output_id. -
render_extra_controls–Optional plot-specific controls rendered between Plot Type and Plot Parameters.
-
render_main_chart–Reactively renders
self.current_chart()fitted to its container. -
resolve_selected_plot–Selects the active plot key given
choicesand the previouscurrent_plot. -
resolved_plot_key–Resolves the currently selected valid plot key for
subject. -
selector_header_ui–Optional status or unlock hint badge rendered above the Plot Type dropdown.
-
server–Binds server logic, state lifecycle, declarative
BaseBinders, and subcomponents to a session. -
sync_version–Updates the recorded version for
keywithout reporting a change. -
ui–Constructs and namespaces the UI tree for this component, adding a resource-gate container if
requiresis set. -
unmet_requirements–Reactively returns the list of currently unmet
Requirementrules. -
val–Safely reads
self.input[id_]()with fallbackdefault, optional reactive isolation, and string stripping.
Attributes:
-
has_session(bool) –Whether this component is currently bound to an active Shiny session.
Source code in src/shiny_kit/explorers.py
has_session
property
¶
has_session: bool
Whether this component is currently bound to an active Shiny session.
active_subject
¶
available_choices
¶
Returns {plot_key: label} choices available for subject.
build_chart
¶
Invokes plotter.plot(subject) (override for plotters requiring special arguments).
has_changed
¶
Tracks version under key and returns True when version differs from the previously recorded value.
Source code in src/shiny_kit/component.py
is_unlocked
¶
is_unlocked() -> bool
Reactively checks whether all declarative requires rules are satisfied.
notify
¶
notify(
message: str,
*,
type_: Literal["message", "warning", "error", "default"] = "message",
duration: int | None = 5,
) -> None
Displays a toast notification if running inside an active Shiny session.
Source code in src/shiny_kit/component.py
notify_error
¶
notify_error(
error: BaseException | str, *, context: str | None = None, duration: int | None = 8
) -> None
Formats and displays an error toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
notify_warning
¶
Displays a warning toast notification in the active Shiny session.
Source code in src/shiny_kit/component.py
render_chart_widget
¶
Renders the shinywidgets.output_widget container for self.chart_output_id.
Source code in src/shiny_kit/explorers.py
render_extra_controls
¶
render_extra_controls(subject: M, plot_key: str) -> TagChild
Optional plot-specific controls rendered between Plot Type and Plot Parameters.
render_main_chart
¶
render_main_chart() -> Any
Reactively renders self.current_chart() fitted to its container.
Source code in src/shiny_kit/explorers.py
resolve_selected_plot
¶
resolve_selected_plot(
subject: M, choices: dict[str, str], current_plot: str | None
) -> str | None
Selects the active plot key given choices and the previous current_plot.
Source code in src/shiny_kit/explorers.py
resolved_plot_key
¶
resolved_plot_key(subject: M) -> str | None
Resolves the currently selected valid plot key for subject.
Source code in src/shiny_kit/explorers.py
selector_header_ui
¶
server
¶
Binds server logic, state lifecycle, declarative BaseBinders, and subcomponents to a session.
Source code in src/shiny_kit/component.py
sync_version
¶
ui
classmethod
¶
Constructs and namespaces the UI tree for this component, adding a resource-gate container if requires is set.
Source code in src/shiny_kit/component.py
unmet_requirements
¶
unmet_requirements() -> list[Requirement]
Reactively returns the list of currently unmet Requirement rules.
Source code in src/shiny_kit/component.py
val
¶
Safely reads self.input[id_]() with fallback default, optional reactive isolation, and string stripping.
Source code in src/shiny_kit/component.py
Introspective Widgets (shiny_kit.widgets)¶
Introspective widget builder (WidgetSelector) and docstring parser (DocstringParser).
Classes:
-
DocstringParser–Extracts parameter documentation from Google-style (
Args:) and NumPy-style (Parameters) docstrings. -
NumericBounds–Declarative numeric input constraints (
min_val,max_val,step) forWidgetSelector. -
ParameterSpec–Introspected metadata for a single
__init__parameter. -
PlotterWidgetSelector–Specialized
WidgetSelectorfor plotter classes with color palettes, hex color pickers, and grouped styling. -
WidgetSelector–Introspects class parameters and maps them to PyShiny input widgets decorated with help tooltips.
DocstringParser
¶
Extracts parameter documentation from Google-style (Args:) and NumPy-style (Parameters) docstrings.
Methods:
-
discover_subclasses–Recursively discovers all concrete (non-abstract) subclasses of
base_cls. -
display_label–Derives a clean human-readable display label from a class docstring or class name.
-
parse_parameters–Parses and caches parameter descriptions from a class and its MRO hierarchy docstrings.
discover_subclasses
staticmethod
¶
discover_subclasses[T](
base_cls: type[T], *, exclude_names: set[str] | None = None
) -> dict[str, type[T]]
Recursively discovers all concrete (non-abstract) subclasses of base_cls.
Parameters:
-
(base_cls¶type[T]) –Abstract or base class whose concrete subclasses should be discovered.
-
(exclude_names¶set[str] | None, default:None) –Optional set of subclass names to exclude from the returned mapping.
Returns:
Source code in src/shiny_kit/widgets.py
display_label
staticmethod
¶
display_label(
target_cls: type[Any], strip_suffix: str = "", *, inherit_doc: bool = True
) -> str
Derives a clean human-readable display label from a class docstring or class name.
Parameters:
-
(target_cls¶type[Any]) –Class to inspect.
-
(strip_suffix¶str, default:'') –Optional class-name suffix to strip when falling back to
__name__. -
(inherit_doc¶bool, default:True) –If
True, inspects MRO viainspect.getdoc(target_cls); ifFalse, only inspectstarget_cls.__dict__.get("__doc__").
Returns:
-
str–Human-readable label string.
Source code in src/shiny_kit/widgets.py
parse_parameters
classmethod
¶
Parses and caches parameter descriptions from a class and its MRO hierarchy docstrings.
Parameters:
Returns:
-
dict[str, str]–Dictionary mapping parameter names to extracted one-line or multi-line descriptions.
Source code in src/shiny_kit/widgets.py
NumericBounds
dataclass
¶
NumericBounds(
min_val: float | int | None = None,
max_val: float | int | None = None,
step: float | int = 1,
)
Declarative numeric input constraints (min_val, max_val, step) for WidgetSelector.
ParameterSpec
dataclass
¶
ParameterSpec(
name: str,
annotation: Any,
default: Any,
docstring: str = "",
is_optional: bool = False,
bounds: NumericBounds | None = None,
)
Introspected metadata for a single __init__ parameter.
Attributes:
-
name(str) –Parameter name.
-
annotation(Any) –Unwrapped type annotation.
-
default(Any) –Default value from
inspect.signature, orinspect.Parameter.empty. -
docstring(str) –Extracted help text from Google or NumPy docstrings.
-
is_optional(bool) –Whether
Noneis an allowed value for this parameter. -
bounds(NumericBounds | None) –Optional resolved numeric bounds for integer/float inputs.
PlotterWidgetSelector
¶
flowchart TD
shiny_kit.widgets.PlotterWidgetSelector[PlotterWidgetSelector]
shiny_kit.widgets.WidgetSelector[WidgetSelector]
shiny_kit.widgets.WidgetSelector --> shiny_kit.widgets.PlotterWidgetSelector
click shiny_kit.widgets.PlotterWidgetSelector href "" "shiny_kit.widgets.PlotterWidgetSelector"
click shiny_kit.widgets.WidgetSelector href "" "shiny_kit.widgets.WidgetSelector"
Specialized WidgetSelector for plotter classes with color palettes, hex color pickers, and grouped styling.
Methods:
-
build_form–Builds Plotter input widgets, grouping low-level styling & dimension controls into a collapsible accordion.
-
default–Returns the process-wide shared default selector instance for
cls. -
extract_kwargs–Extracts and casts values from Shiny's
Inputsor a mapping to pass intotarget_cls(**kwargs). -
introspect–Introspects and caches
__init__parameters, walking the MRO when**kwargsis forwarded to superclasses. -
register–Decorator to register a custom widget builder rule (evaluated first).
Source code in src/shiny_kit/widgets.py
build_form
¶
build_form(
target_cls: type[Any],
*,
exclude: set[str] | None = None,
choices: Mapping[str, Sequence[str] | Mapping[str, str]] | None = None,
prefix: str = "",
group_styling: bool = True,
) -> list[TagChild]
Builds Plotter input widgets, grouping low-level styling & dimension controls into a collapsible accordion.
Source code in src/shiny_kit/widgets.py
default
classmethod
¶
default() -> Self
Returns the process-wide shared default selector instance for cls.
Source code in src/shiny_kit/widgets.py
extract_kwargs
¶
extract_kwargs(
target_cls: type[Any],
inputs: Inputs | Mapping[str, Any],
*,
exclude: set[str] | None = None,
prefix: str = "",
) -> dict[str, Any]
Extracts and casts values from Shiny's Inputs or a mapping to pass into target_cls(**kwargs).
Source code in src/shiny_kit/widgets.py
introspect
¶
Introspects and caches __init__ parameters, walking the MRO when **kwargs is forwarded to superclasses.
Source code in src/shiny_kit/widgets.py
WidgetSelector
¶
Introspects class parameters and maps them to PyShiny input widgets decorated with help tooltips.
Target classes may optionally declare class attributes __widget_exclude__: ClassVar[Collection[str]]
and __widget_constraints__: ClassVar[Mapping[str, NumericBounds | tuple[float | int | None, float | int | None, float | int]]]
across their MRO to customize parameter exclusions and numeric input bounds without importing shiny_kit.
Attributes:
-
default_exclude(ClassVar[set[str]]) –Parameter names excluded by default during introspection.
-
non_ui_types(ClassVar[tuple[type[Any], ...]]) –Parameter types (such as RNG instances) that should be automatically omitted from generated UI forms.
Examples:
from shiny_kit.widgets import WidgetSelector
class ModelConfig:
def __init__(self, alpha: float = 0.05, method: str = "exact") -> None:
self.alpha = alpha
self.method = method
selector = WidgetSelector.default()
widgets = selector.build_form(ModelConfig, prefix="cfg_")
Methods:
-
build_form–Builds a collection of Shiny input widgets for the target class.
-
default–Returns the process-wide shared default selector instance for
cls. -
extract_kwargs–Extracts and casts values from Shiny's
Inputsor a mapping to pass intotarget_cls(**kwargs). -
introspect–Introspects and caches
__init__parameters, walking the MRO when**kwargsis forwarded to superclasses. -
register–Decorator to register a custom widget builder rule (evaluated first).
Source code in src/shiny_kit/widgets.py
build_form
¶
build_form(
target_cls: type[Any],
*,
exclude: set[str] | None = None,
choices: Mapping[str, Sequence[str] | Mapping[str, str]] | None = None,
prefix: str = "",
) -> list[TagChild]
Builds a collection of Shiny input widgets for the target class.
Source code in src/shiny_kit/widgets.py
default
classmethod
¶
default() -> Self
Returns the process-wide shared default selector instance for cls.
Source code in src/shiny_kit/widgets.py
extract_kwargs
¶
extract_kwargs(
target_cls: type[Any],
inputs: Inputs | Mapping[str, Any],
*,
exclude: set[str] | None = None,
prefix: str = "",
) -> dict[str, Any]
Extracts and casts values from Shiny's Inputs or a mapping to pass into target_cls(**kwargs).
Source code in src/shiny_kit/widgets.py
introspect
¶
Introspects and caches __init__ parameters, walking the MRO when **kwargs is forwarded to superclasses.
Source code in src/shiny_kit/widgets.py
UI Primitives (shiny_kit.ui)¶
Stateless UI layout primitives (Icon, EmptyState, KPICard, KPIRow), reactive StagedList, and app footer/CLI helpers.
Classes:
-
EcosystemPillarSpec–Specification for an ecosystem pillar pill in
package_footer(). -
EmptyState–Declarative empty-state placeholder card with a Lucide icon, title, and muted description.
-
Icon–Renders Lucide SVG icons wrapped in
htmltools.HTMLfor PyShiny UI elements. -
KPICard–Declarative summary metric card inside a
KPIRow. -
KPIRow–Responsive Bootstrap row of
KPICardsummary metrics. -
PackageMetadata–Resolved Python distribution metadata extracted from
importlib.metadataorpyproject.toml. -
StagedList–Per-instance reactive list of staged items with UI badge and button helpers.
Functions:
-
build_cli_parser–Constructs a standard CLI argument parser for a
shiny-kitweb application. -
package_footer–Renders a 2-zone glassmorphic application footer populated from
PackageMetadataand optional ecosystem pills. -
run_cli–Parses CLI arguments and launches the PyShiny application via
shiny._main.run_app.
EcosystemPillarSpec
dataclass
¶
EcosystemPillarSpec(
name: str,
slug: str,
icon: str,
url: str,
description: str,
is_active: bool = False,
color: str = "#7c3aed",
dark_color: str | None = None,
)
Specification for an ecosystem pillar pill in package_footer().
Attributes:
-
name(str) –Display name of the pillar.
-
slug(str) –CSS modifier slug (e.g.
"seroverse","seroref","kbank","serogen","seroepi"). -
icon(str) –Lucide icon identifier.
-
url(str) –Documentation or landing page URL.
-
description(str) –Tooltip summary of the pillar's role.
-
is_active(bool) –Whether this pillar corresponds to the running application.
-
color(str) –Light-mode accent color for the pillar icon/active badge.
-
dark_color(str | None) –Optional dark-mode accent color override.
EmptyState
dataclass
¶
EmptyState(
icon: str,
title: str,
message: str,
dashed: bool = False,
compact: bool = False,
icon_size: int = 36,
)
Declarative empty-state placeholder card with a Lucide icon, title, and muted description.
Attributes:
-
icon(str) –Lucide icon name.
-
title(str) –Primary heading text.
-
message(str) –Secondary explanatory paragraph text.
-
dashed(bool) –Whether to render a dashed border instead of a solid card background.
-
compact(bool) –Whether to use tighter vertical padding.
-
icon_size(int) –Pixel size of the Lucide icon. Defaults to
36.
Examples:
from shiny_kit.ui import EmptyState
placeholder = EmptyState(
icon="database",
title="No Dataset Loaded",
message="Upload or select a benchmark cohort in the sidebar.",
)
tag = placeholder.ui()
Methods:
-
ui–Renders the empty-state Bootstrap container.
ui
¶
Renders the empty-state Bootstrap container.
Returns:
-
Tag–Bootstrap
divtag containing the icon, title, and message.
Source code in src/shiny_kit/ui.py
Icon
¶
Renders Lucide SVG icons wrapped in htmltools.HTML for PyShiny UI elements.
Examples:
Methods:
-
github–Returns the official GitHub Octocat mark as an inline SVG inheriting
currentColor. -
lucide–Render a Lucide SVG icon wrapped in
htmltools.HTMLfor Shiny UI integration. -
pypi–Returns the official PyPI isometric cube mark as an inline SVG inheriting
currentColor.
github
classmethod
¶
github(size: int = 14) -> HTML
Returns the official GitHub Octocat mark as an inline SVG inheriting currentColor.
Source code in src/shiny_kit/ui.py
lucide
classmethod
¶
Render a Lucide SVG icon wrapped in htmltools.HTML for Shiny UI integration.
Parameters:
-
(name¶str | None) –Lucide icon identifier (e.g.
"database","shield-check"), orNone. -
(size¶int, default:18) –Width and height of the rendered SVG in pixels. Defaults to
18. -
(class_¶str, default:'me-1') –CSS classes appended to
"lucide-icon". Defaults to"me-1". -
(**kwargs¶Any, default:{}) –Additional SVG attributes forwarded to
lucide._render_icon.
Returns:
-
HTML | None–htmltools.HTMLcontaining the<svg>markup, orNoneifnameisNone.
Raises:
-
ValueError–If
namedoes not match a valid Lucide icon.
Source code in src/shiny_kit/ui.py
pypi
classmethod
¶
pypi(size: int = 14) -> HTML
Returns the official PyPI isometric cube mark as an inline SVG inheriting currentColor.
Source code in src/shiny_kit/ui.py
KPICard
dataclass
¶
KPICard(
label: str,
value: str,
subtitle: str = "",
col_width: int = 3,
value_class: str = "fs-5",
subtitle_class: str = "text-muted",
truncate_subtitle: bool = False,
tooltip: str | None = None,
)
Declarative summary metric card inside a KPIRow.
Attributes:
-
label(str) –Muted top label describing the metric.
-
value(str) –Bold primary value text.
-
subtitle(str) –Secondary caption beneath the primary value.
-
col_width(int) –Bootstrap 12-column grid span (
col-md-{col_width}). Defaults to3. -
value_class(str) –Additional CSS classes applied to the primary value element.
-
subtitle_class(str) –Additional CSS classes applied to the subtitle element.
-
truncate_subtitle(bool) –Whether to apply
text-truncateand a hovertitleattribute to the subtitle. -
tooltip(str | None) –Optional hover tooltip text for the subtitle.
Methods:
-
ui–Renders the responsive Bootstrap column and bordered metric card.
ui
¶
Renders the responsive Bootstrap column and bordered metric card.
Returns:
-
Tag–Bootstrap
divcolumn containing the formatted KPI card.
Source code in src/shiny_kit/ui.py
KPIRow
dataclass
¶
PackageMetadata
dataclass
¶
PackageMetadata(
name: str,
version: str,
summary: str,
author: str,
author_email: str,
author_url: str,
homepage: str,
documentation: str,
repository: str,
bug_tracker: str,
changelog: str,
pypi_url: str,
license_spdx: str = "GPL-3.0",
)
Resolved Python distribution metadata extracted from importlib.metadata or pyproject.toml.
Attributes:
-
name(str) –Distribution package name.
-
version(str) –Full PEP 440 version string (including any
.devor+g...suffix). -
summary(str) –One-line package summary description.
-
author(str) –Primary author name.
-
author_email(str) –Primary author contact email address.
-
author_url(str) –Author website URL.
-
homepage(str) –Canonical documentation / homepage URL.
-
documentation(str) –Documentation site URL.
-
repository(str) –Source code GitHub repository URL.
-
bug_tracker(str) –Issue tracker URL.
-
changelog(str) –Changelog URL.
-
pypi_url(str) –PyPI package project URL.
-
license_spdx(str) –Short license identifier (
"GPL-3.0").
Methods:
-
load–Loads distribution metadata via
importlib.metadatawith apyproject.tomlfallback.
short_version
property
¶
short_version: str
Returns the version string with any local +g... git build suffix removed for compact display.
load
cached
classmethod
¶
load(
package_name: str = "shiny-kit", *, pyproject_path: Path | None = None
) -> PackageMetadata
Loads distribution metadata via importlib.metadata with a pyproject.toml fallback.
Parameters:
-
(package_name¶str, default:'shiny-kit') –Installed Python distribution name to inspect.
-
(pyproject_path¶Path | None, default:None) –Optional explicit path to
pyproject.tomlwhen uninstalled.
Returns:
-
PackageMetadata–Populated
PackageMetadatainstance.
Source code in src/shiny_kit/ui.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | |
StagedList
¶
StagedList(initial: Iterable[T] = ())
Per-instance reactive list of staged items with UI badge and button helpers.
Methods:
-
action_buttons–Renders a compact horizontal toolbar of Add / Remove Last / Clear action buttons.
-
add–Appends
itemto the staged collection. -
clear–Clears all staged items.
-
pop–Removes and returns the last staged item, if any.
-
remove_at–Removes the item at
indexif in range. -
render_badges–Renders the staged items using
formatter(index, item)or an empty caption. -
set–Replaces the staged items.
Attributes:
-
is_empty(bool) –Reactively returns True when no items are staged.
-
items(list[T]) –Reactively returns the staged items as a list.
Source code in src/shiny_kit/ui.py
action_buttons
staticmethod
¶
action_buttons(
add_id: str,
*,
add_label: str = "Add",
pop_id: str | None = None,
pop_label: str = "Remove Last",
clear_id: str | None = None,
clear_label: str = "Clear",
) -> Tag
Renders a compact horizontal toolbar of Add / Remove Last / Clear action buttons.
Source code in src/shiny_kit/ui.py
add
¶
add(item: T, *, deduplicate: bool = False) -> None
Appends item to the staged collection.
Source code in src/shiny_kit/ui.py
clear
¶
pop
¶
Removes and returns the last staged item, if any.
render_badges
¶
render_badges(
formatter: Callable[[int, T], TagChild],
*,
empty_text: str = "No items staged yet.",
wrapper_class: str = "",
) -> TagChild
Renders the staged items using formatter(index, item) or an empty caption.
Source code in src/shiny_kit/ui.py
build_cli_parser
¶
build_cli_parser(
prog: str,
*,
package_name: str | None = None,
description: str = "Launch the interactive PyShiny web application.",
version: str | None = None,
default_host: str = "127.0.0.1",
default_port: int = 8000,
) -> ArgumentParser
Constructs a standard CLI argument parser for a shiny-kit web application.
Parameters:
-
(prog¶str) –CLI program name (e.g.
"seroepi-app"). -
(package_name¶str | None, default:None) –Optional distribution name used to resolve
--versionviaPackageMetadata.load(). -
(description¶str, default:'Launch the interactive PyShiny web application.') –CLI help description string.
-
(version¶str | None, default:None) –Optional explicit version string overriding
PackageMetadata.load(package_name).version. -
(default_host¶str, default:'127.0.0.1') –Default bind host address. Defaults to
"127.0.0.1". -
(default_port¶int, default:8000) –Default bind port number. Defaults to
8000.
Returns:
-
ArgumentParser–Configured
argparse.ArgumentParser.
Source code in src/shiny_kit/ui.py
package_footer
¶
package_footer(
package_name: str = "shiny-kit",
*,
brand_title: str | None = None,
brand_icon: str = "chart-network",
author_url: str | None = None,
meta: PackageMetadata | None = None,
pillars: Sequence[EcosystemPillarSpec] = (),
) -> Tag
Renders a 2-zone glassmorphic application footer populated from PackageMetadata and optional ecosystem pills.
Parameters:
-
(package_name¶str, default:'shiny-kit') –Distribution name used when
metais omitted. -
(brand_title¶str | None, default:None) –Display title for the brand link. Defaults to
meta.name. -
(brand_icon¶str, default:'chart-network') –Lucide icon name for the brand mark. Defaults to
"chart-network". -
(author_url¶str | None, default:None) –Optional explicit author profile URL overriding
meta.author_url. -
(meta¶PackageMetadata | None, default:None) –Optional pre-loaded
PackageMetadatainstance. -
(pillars¶Sequence[EcosystemPillarSpec], default:()) –Optional sequence of
EcosystemPillarSpecitems rendered in the right zone.
Returns:
-
Tag–shiny.ui.Tag<footer>element suitable forshiny.ui.page_navbar(footer=...).
Source code in src/shiny_kit/ui.py
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 | |
run_cli
¶
run_cli(
app_target: str,
*,
parser: ArgumentParser | None = None,
prog: str = "shiny-kit-app",
package_name: str | None = None,
description: str = "Launch the interactive PyShiny web application.",
reload_dirs: Sequence[str | Path] | None = None,
app_dir: str | Path | None = None,
argv: Sequence[str] | None = None,
) -> int
Parses CLI arguments and launches the PyShiny application via shiny._main.run_app.
Parameters:
-
(app_target¶str) –Module/attribute target string passed to
run_app(e.g."seroepi.app.app:app"). -
(parser¶ArgumentParser | None, default:None) –Optional pre-built
argparse.ArgumentParser. -
(prog¶str, default:'shiny-kit-app') –CLI program name when
parseris not supplied. -
(package_name¶str | None, default:None) –Optional distribution name when
parseris not supplied. -
(description¶str, default:'Launch the interactive PyShiny web application.') –CLI description when
parseris not supplied. -
(reload_dirs¶Sequence[str | Path] | None, default:None) –Optional directories watched when
--reloadis active. -
(app_dir¶str | Path | None, default:None) –Optional root directory added to
sys.pathbyrun_app. -
(argv¶Sequence[str] | None, default:None) –Optional sequence of command-line arguments (defaults to
sys.argv[1:]).
Returns:
-
int–Exit status code
0.
Source code in src/shiny_kit/ui.py
Caching (shiny_kit.caching)¶
Pure-stdlib two-tier content-addressable cache with LRU memory and pluggable disk persistence.
Classes:
-
BaseCache–Thread-safe two-tier content-addressable cache (in-memory LRU + pluggable disk tier).
BaseCache
¶
BaseCache(
cache_dir: str | Path | None = None,
*,
max_memory_items: int = 64,
persist_to_disk: bool = True,
)
Thread-safe two-tier content-addressable cache (in-memory LRU + pluggable disk tier).
Provides deterministic SHA-256 fingerprinting across primitives, paths, dataclasses,
collections, and objects implementing __cache_fingerprint__(), alongside single-flight
per-key locking so concurrent callers computing the same key wait on the first computation.
Subclasses can override _update_custom_hasher() to fingerprint domain-specific types
(e.g. DataFrames or ML estimators) and _dump_to_disk() / _load_from_disk() for custom
serialization formats (e.g. joblib).
Attributes:
-
disk_extension(ClassVar[str]) –File extension used for disk cache entries. Defaults to
".pkl". -
env_prefix(ClassVar[str]) –Environment variable prefix (
{env_prefix}_CACHE_DIR,{env_prefix}_HOME). -
default_home_dirname(ClassVar[str]) –Default home directory folder name. Defaults to
".shiny-kit".
Parameters:
-
(cache_dir¶str | Path | None, default:None) –Optional directory path for persistent disk storage.
-
(max_memory_items¶int, default:64) –Maximum number of items retained in the in-memory LRU tier.
-
(persist_to_disk¶bool, default:True) –Whether to persist cached values to disk.
Methods:
-
acall_or_load–Asynchronously executes
await fn(*args, **kwargs)with single-flight fingerprint caching. -
call_or_load–Executes
fn(*args, **kwargs)with thread-safe two-tier fingerprint caching. -
clear–Clears both the in-memory LRU cache and persistent disk artifacts.
-
compute_fit_key–Computes a composite cache key for fitting
estimatoron(X, y). -
fingerprint–Computes a deterministic 32-character SHA-256 hex digest for
obj. -
fit_or_load–Returns a cached fitted clone of
estimatoron(X, y), or fits and caches it on miss. -
get–Looks up a cached artifact by fingerprint key across memory and disk tiers.
-
get_default_cache_dir–Resolves the persistent cache directory from environment variables or
~/.shiny-kit/cache. -
put–Stores an artifact in the in-memory LRU and optional disk tier atomically.
Source code in src/shiny_kit/caching.py
acall_or_load
async
¶
acall_or_load[R](
fn: Callable[..., Awaitable[R]],
*args: Any,
force_refresh: bool = False,
**kwargs: Any,
) -> R
Asynchronously executes await fn(*args, **kwargs) with single-flight fingerprint caching.
Parameters:
-
(fn¶Callable[..., Awaitable[R]]) –Async callable to await on cache miss.
-
(*args¶Any, default:()) –Positional arguments forwarded to
fn. -
(force_refresh¶bool, default:False) –If
True, bypasses cached values and recomputesfn. -
(**kwargs¶Any, default:{}) –Keyword arguments forwarded to
fn.
Returns:
-
R–Cached or freshly computed return value
R.
Source code in src/shiny_kit/caching.py
call_or_load
¶
call_or_load[R](
fn: Callable[..., R], *args: Any, force_refresh: bool = False, **kwargs: Any
) -> R
Executes fn(*args, **kwargs) with thread-safe two-tier fingerprint caching.
Parameters:
-
(fn¶Callable[..., R]) –Callable to execute on cache miss.
-
(*args¶Any, default:()) –Positional arguments forwarded to
fn. -
(force_refresh¶bool, default:False) –If
True, bypasses cached values and recomputesfn. -
(**kwargs¶Any, default:{}) –Keyword arguments forwarded to
fn.
Returns:
-
R–Cached or freshly computed return value
R.
Source code in src/shiny_kit/caching.py
clear
¶
Clears both the in-memory LRU cache and persistent disk artifacts.
Source code in src/shiny_kit/caching.py
compute_fit_key
¶
Computes a composite cache key for fitting estimator on (X, y).
Parameters:
-
(estimator¶Any) –Unfitted or configured estimator instance.
-
(X¶Any) –Input data object.
-
(y¶Any, default:None) –Optional target argument.
Returns:
-
str–32-character SHA-256 fingerprint string.
Source code in src/shiny_kit/caching.py
fingerprint
classmethod
¶
Computes a deterministic 32-character SHA-256 hex digest for obj.
Parameters:
Returns:
-
str–32-character hexadecimal SHA-256 fingerprint string.
Source code in src/shiny_kit/caching.py
fit_or_load
¶
Returns a cached fitted clone of estimator on (X, y), or fits and caches it on miss.
Uses per-key single-flight locking so concurrent sessions fitting the same model and
dataset wait on the first fit and share its cached output without redundant execution.
Captures and re-emits user-facing warnings via WarningCatcher.
Parameters:
-
(estimator¶E) –Unfitted or configured estimator implementing
.fit(X)/.fit(X, y). -
(X¶Any, default:None) –Input data (or
Nonewhen wrapping pre-fitted models). -
(y¶Any, default:None) –Optional target argument.
Returns:
-
E–The fitted estimator instance.
Source code in src/shiny_kit/caching.py
get
¶
Looks up a cached artifact by fingerprint key across memory and disk tiers.
Parameters:
Returns:
Source code in src/shiny_kit/caching.py
get_default_cache_dir
classmethod
¶
get_default_cache_dir() -> Path
Resolves the persistent cache directory from environment variables or ~/.shiny-kit/cache.
Source code in src/shiny_kit/caching.py
put
¶
Stores an artifact in the in-memory LRU and optional disk tier atomically.
Parameters:
Returns:
-
Any–The stored
value.
Source code in src/shiny_kit/caching.py
Progress Reporting (shiny_kit.progress)¶
Zero-dependency, context-propagated hierarchical progress reporting.
Classes:
-
LazyShinyProgress–Thread-safe lazy bridge from
ProgressReportertoshiny.ui.Progress. -
ProgressReporter–Hierarchical, rate-throttled progress reporter with sub-range composition.
Functions:
-
current_progress–Returns the context-local
ProgressReporter(or a zero-cost no-op reporter if unbound). -
progress_context–Binds a root
ProgressReporterto the current execution context (propagates intoasyncio.to_thread).
LazyShinyProgress
¶
LazyShinyProgress(
session: Session | None,
*,
default_message: str = "Working...",
grace_sec: float = 0.15,
loop: AbstractEventLoop | None = None,
progress_factory: Callable[[], Any] | None = None,
)
Thread-safe lazy bridge from ProgressReporter to shiny.ui.Progress.
Suppresses opening the Shiny progress notification if the task finishes within
grace_sec (default 150ms), so instant BaseCache hits or trivial operations
never flash a progress bar. If the task is still running after grace_sec, opens
and updates shiny.ui.Progress on the main asyncio event loop.
Methods:
-
close–Cancels any pending grace timer and closes the Shiny progress bar if opened.
-
update–Records the latest milestone and dispatches to the Shiny event loop if past grace period.
Source code in src/shiny_kit/progress.py
close
¶
Cancels any pending grace timer and closes the Shiny progress bar if opened.
Source code in src/shiny_kit/progress.py
update
¶
Records the latest milestone and dispatches to the Shiny event loop if past grace period.
Source code in src/shiny_kit/progress.py
ProgressReporter
dataclass
¶
ProgressReporter(
_shared: _SharedProgressState = (lambda: _SharedProgressState(callback=None))(),
start: float = 0.0,
end: float = 1.0,
default_message: str | None = None,
detail_prefix: str | None = None,
)
Hierarchical, rate-throttled progress reporter with sub-range composition.
Maps local progress fractions in [0.0, 1.0] into [start, end] of the root task,
ensuring nested estimators and cross-validation folds advance monotonically from 0% to 100%.
Attributes:
-
start(float) –Lower bound of this reporter's progress interval within
[0.0, 1.0]. -
end(float) –Upper bound of this reporter's progress interval within
[0.0, 1.0]. -
default_message(str | None) –Default primary status message when
report()omitsmessage. -
detail_prefix(str | None) –Optional hierarchical prefix prepended to
detailstrings.
Examples:
from shiny_kit.progress import current_progress, progress_context
events = []
with progress_context(lambda frac, msg, det: events.append((frac, msg, det))):
prog = current_progress()
prog.report(0.2, message="Loading data")
with prog.subrange(0.2, 1.0, detail_prefix="Fold 1"):
current_progress().report(0.5, detail="Fitting")
Methods:
-
report–Emits a progress update mapped into
[self.start, self.end]. -
subrange–Scopes nested
current_progress()calls into[start, end]of the current range.
is_active
property
¶
is_active: bool
Whether an active listener callback is bound to this reporter.
Returns:
-
bool–Trueif aProgressCallbackis attached,Falsefor the default no-op reporter.
report
¶
report(
fraction: float,
message: str | None = None,
detail: str | None = None,
*,
force: bool = False,
) -> None
Emits a progress update mapped into [self.start, self.end].
Parameters:
-
(fraction¶float) –Local completion fraction in
[0.0, 1.0]. -
(message¶str | None, default:None) –Optional primary status heading.
-
(detail¶str | None, default:None) –Optional secondary detail string.
-
(force¶bool, default:False) –If
True, bypasses rate-limitingmin_interval_secthrottling.
Source code in src/shiny_kit/progress.py
subrange
¶
subrange(
start: float,
end: float,
*,
message: str | None = None,
detail_prefix: str | None = None,
) -> Generator[ProgressReporter]
Scopes nested current_progress() calls into [start, end] of the current range.
Parameters:
-
(start¶float) –Relative start fraction in
[0.0, 1.0]within the parent reporter's range. -
(end¶float) –Relative end fraction in
[start, 1.0]within the parent reporter's range. -
(message¶str | None, default:None) –Optional override for
default_messageinside the subrange. -
(detail_prefix¶str | None, default:None) –Optional prefix prepended to nested
detailstrings.
Yields:
-
Generator[ProgressReporter]–Scoped child
ProgressReporterbound to_ACTIVE_PROGRESS.
Source code in src/shiny_kit/progress.py
current_progress
¶
current_progress() -> ProgressReporter
Returns the context-local ProgressReporter (or a zero-cost no-op reporter if unbound).
Returns:
-
ProgressReporter–Active
ProgressReporterfor the current execution context.
Source code in src/shiny_kit/progress.py
progress_context
¶
progress_context(
callback: ProgressCallback,
*,
message: str | None = None,
min_interval_sec: float = 0.0,
) -> Generator[ProgressReporter]
Binds a root ProgressReporter to the current execution context (propagates into asyncio.to_thread).
Parameters:
-
(callback¶ProgressCallback) –Listener callable
(fraction, message, detail) -> Noneinvoked on progress updates. -
(message¶str | None, default:None) –Optional initial default status message.
-
(min_interval_sec¶float, default:0.0) –Minimum elapsed seconds between consecutive non-final progress emissions.
Yields:
-
Generator[ProgressReporter]–Root
ProgressReporterbound to the currentcontextvarscontext.
Source code in src/shiny_kit/progress.py
Warning Capture (shiny_kit.warnings)¶
Context manager for intercepting, filtering, and deduplicating user-facing warnings.
Classes:
-
WarningCatcher–Context manager that intercepts, filters, deduplicates, and optionally re-emits user-facing warnings.
WarningCatcher
¶
Context manager that intercepts, filters, deduplicates, and optionally re-emits user-facing warnings.
Attributes:
-
reemit_on_exit(bool) –Whether captured warnings should be re-emitted via
warnings.warnon__exit__. -
messages(tuple[str, ...]) –Deduplicated tuple of captured warning strings after context exit.
Examples:
import warnings
from shiny_kit.warnings import WarningCatcher
with WarningCatcher() as catcher:
warnings.warn("Unpadded strata detected", UserWarning)
assert catcher.messages == ("Unpadded strata detected",)
Parameters:
-
(reemit¶bool, default:False) –Whether to re-emit captured user warnings when exiting the
withblock.
Methods:
-
__enter__–Enters the
warnings.catch_warnings(record=True)context. -
__exit__–Exits the warning capture context, populates
self.messages, and optionally re-emits. -
emit_messages–Emits each message in
messagesas a standardUserWarning. -
is_relevant–Returns True if
wis an explicitUserWarningor originates from non-library application code. -
merge–Deduplicates warning messages across iterables while preserving first-seen order.
Source code in src/shiny_kit/warnings.py
__exit__
¶
__exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exits the warning capture context, populates self.messages, and optionally re-emits.
Source code in src/shiny_kit/warnings.py
emit_messages
staticmethod
¶
emit_messages(messages: Iterable[str], *, stacklevel: int = 2) -> None
Emits each message in messages as a standard UserWarning.
Parameters:
-
(messages¶Iterable[str]) –Iterable of warning strings to emit.
-
(stacklevel¶int, default:2) –Stack level passed to
warnings.warn. Defaults to2.
Source code in src/shiny_kit/warnings.py
is_relevant
staticmethod
¶
Returns True if w is an explicit UserWarning or originates from non-library application code.
Parameters:
-
(w¶WarningMessage) –Recorded
warnings.WarningMessageinstance.
Returns:
-
bool–Trueif the warning should be surfaced to the user,Falseotherwise.
Source code in src/shiny_kit/warnings.py
merge
staticmethod
¶
merge(*message_iters: Iterable[str]) -> tuple[str, ...]
Deduplicates warning messages across iterables while preserving first-seen order.
Parameters:
-
(*message_iters¶Iterable[str], default:()) –Variable number of iterables yielding warning strings.
Returns: