Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

docs: update UI plugin docstrings to Google Style format (#3206)

devin-ai-integration[bot]452b95e72b7b
diff --git a/marimo/_plugins/stateless/flex.py b/marimo/_plugins/stateless/flex.py
index a34c74b522..45cc38db38 100644
--- a/marimo/_plugins/stateless/flex.py
+++ b/marimo/_plugins/stateless/flex.py
@@ -81,37 +81,40 @@ def vstack(
Combine with `hstack` to build a grid of items.
- **Example.**
-
- ```python3
- # Build a column of items
- mo.vstack([mo.md("..."), mo.ui.text_area()])
- ```
-
- ```python3
- # Build a grid.
- mo.vstack(
- [
- mo.hstack([mo.md("..."), mo.ui.text_area()]),
- mo.hstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
- ]
- )
- ```
-
- **Args.**
-
- - `items`: A list of items.
- - `align`: Align items horizontally: start, end, center, or stretch.
- - `justify`: Justify items vertically: start, center, end,
- - `gap`: Gap between items as a float in rem. 1rem is 16px by default.
- - `heights`: "equal" to give items equal height;
- or a list of relative heights with same length as `items`,
- eg, [1, 2] means the second item is twice as tall
- as the first; or `None` for a sensible default
-
- **Returns.**
-
- - An `Html` object.
+ Examples:
+ Build a column of items:
+ ```python
+ # Build a column of items
+ mo.vstack([mo.md("..."), mo.ui.text_area()])
+ ```
+
+ Build a grid:
+ ```python
+ # Build a grid.
+ mo.vstack(
+ [
+ mo.hstack([mo.md("..."), mo.ui.text_area()]),
+ mo.hstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
+ ]
+ )
+ ```
+
+ Args:
+ items (Sequence[object]): A list of items.
+ align (Literal["start", "end", "center", "stretch"], optional): Align items
+ horizontally: start, end, center, or stretch.
+ justify (Literal["start", "center", "end", "space-between", "space-around"]):
+ Justify items vertically: start, center, end, space-between, or space-around.
+ Defaults to "start".
+ gap (float, optional): Gap between items as a float in rem. 1rem is 16px by default.
+ Defaults to 0.5.
+ heights (Union[Literal["equal"], Sequence[float]], optional): "equal" to give items
+ equal height; or a list of relative heights with same length as `items`,
+ eg, [1, 2] means the second item is twice as tall as the first;
+ or None for a sensible default.
+
+ Returns:
+ Html: An Html object.
"""
return _flex(
items,
@@ -142,38 +145,41 @@ def hstack(
Combine with `vstack` to build a grid.
- **Example.**
-
- ```python3
- # Build a row of items
- mo.hstack([mo.md("..."), mo.ui.text_area()])
- ```
-
- ```python3
- # Build a grid.
- mo.hstack(
- [
- mo.vstack([mo.md("..."), mo.ui.text_area()]),
- mo.vstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
- ]
- )
- ```
-
- **Args.**
-
- - `items`: A list of items.
- - `justify`: Justify items horizontally: start, center, end,
- space-between, or space-around.
- - `align`: Align items vertically: start, end, center, or stretch.
- - `wrap`: Wrap items or not.
- - `gap`: Gap between items as a float in rem. 1rem is 16px by default.
- - `widths`: "equal" to give items equal width; or a list of relative widths
- with same length as `items`, eg, [1, 2] means the second item is twice as
- wide as the first; or `None` for a sensible default
-
- **Returns.**
-
- - An `Html` object.
+ Examples:
+ Build a row of items:
+ ```python
+ # Build a row of items
+ mo.hstack([mo.md("..."), mo.ui.text_area()])
+ ```
+
+ Build a grid:
+ ```python
+ # Build a grid.
+ mo.hstack(
+ [
+ mo.vstack([mo.md("..."), mo.ui.text_area()]),
+ mo.vstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
+ ]
+ )
+ ```
+
+ Args:
+ items (Sequence[object]): A list of items.
+ justify (Literal["start", "center", "end", "space-between", "space-around"]):
+ Justify items horizontally: start, center, end, space-between, or space-around.
+ Defaults to "space-between".
+ align (Literal["start", "end", "center", "stretch"], optional): Align items
+ vertically: start, end, center, or stretch.
+ wrap (bool, optional): Wrap items or not. Defaults to False.
+ gap (float, optional): Gap between items as a float in rem. 1rem is 16px by default.
+ Defaults to 0.5.
+ widths (Union[Literal["equal"], Sequence[float]], optional): "equal" to give items
+ equal width; or a list of relative widths with same length as `items`,
+ eg, [1, 2] means the second item is twice as wide as the first;
+ or None for a sensible default.
+
+ Returns:
+ Html: An Html object.
"""
return _flex(
items,
diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.py
index 83d057b289..547c5c39a9 100644
--- a/marimo/_plugins/stateless/lazy.py
+++ b/marimo/_plugins/stateless/lazy.py
@@ -30,38 +30,32 @@ class lazy(UIElement[bool, bool]):
Using a function is useful when the item to render is
the result of a database query or some other expensive operation.
- **Examples.**
-
- Create a lazy-loaded tab:
-
- ```python
- tabs = mo.ui.tabs(
- {"Overview": tab1, "Charts": mo.lazy(expensive_component)}
- )
- ```
-
- Create a lazy-loaded accordion:
-
- ```python
- accordion = mo.ui.accordion({"Charts": mo.lazy(expensive_component)})
- ```
-
- Usage with async functions:
-
- ```python
- async def expensive_component(): ...
+ Examples:
+ Create a lazy-loaded tab:
+ ```python
+ tabs = mo.ui.tabs(
+ {"Overview": tab1, "Charts": mo.lazy(expensive_component)}
+ )
+ ```
+ Create a lazy-loaded accordion:
+ ```python
+ accordion = mo.ui.accordion({"Charts": mo.lazy(expensive_component)})
+ ```
- mo.lazy(expensive_component)
- ```
+ Usage with async functions:
+ ```python
+ async def expensive_component(): ...
- **Initialization Args.**
+ mo.lazy(expensive_component)
+ ```
- - `element`: object or callable that returns content to be lazily loaded
- - `show_loading_indicator`: a boolean, whether to show a loading
- indicator while the content is being loaded.
- Default is `False`.
+ Args:
+ element (Union[Callable[[], object], object, Callable[[], Coroutine[None, None, object]]]):
+ Object or callable that returns content to be lazily loaded.
+ show_loading_indicator (bool, optional): Whether to show a loading indicator
+ while the content is being loaded. Defaults to False.
"""
_name: Final[str] = "marimo-lazy"
diff --git a/marimo/_plugins/stateless/routes.py b/marimo/_plugins/stateless/routes.py
index 11243d9ea8..1913bf97a4 100644
--- a/marimo/_plugins/stateless/routes.py
+++ b/marimo/_plugins/stateless/routes.py
@@ -12,44 +12,37 @@ from marimo._plugins.ui._core.ui_element import UIElement
@mddoc
class routes(UIElement[str, str]):
- """
- Renders a list of routes that are switched based on the
- URL path.
+ """Renders a list of routes that are switched based on the URL path.
- Routes currently don't support nested routes, or
- dynamic routes (e.g. `#/user/:id`). If you'd like to
- see these features, please let us know on GitHub:
+ Routes currently don't support nested routes, or dynamic routes (e.g. `#/user/:id`).
+ If you'd like to see these features, please let us know on GitHub:
https://github.com/marimo-team/marimo/issues
- For a simple-page-application (SPA) experience, you
- should use hash-based routing. For example, prefix
- your routes with `#/`.
-
- If you are using a multi-page-application (MPA) with
- `marimo.create_asgi_app`, you should use path-based routing.
- For example, prefix your routes with `/`.
-
- **Examples.**
-
- ```python
- mo.routes(
- {
- "#/": render_home,
- "#/about": render_about,
- "#/contact": render_contact,
- mo.routes.CATCH_ALL: render_home,
- }
- )
- ```
-
- **Args.**
-
- - `routes`: a dictionary of routes, where the key is the URL path
- and the value is a function that returns the content to display.
+ For a simple-page-application (SPA) experience, you should use hash-based routing.
+ For example, prefix your routes with `#/`.
+
+ If you are using a multi-page-application (MPA) with `marimo.create_asgi_app`,
+ you should use path-based routing. For example, prefix your routes with `/`.
+
+ Examples:
+ ```python
+ mo.routes(
+ {
+ "#/": render_home,
+ "#/about": render_about,
+ "#/contact": render_contact,
+ mo.routes.CATCH_ALL: render_home,
+ }
+ )
+ ```
- **Returns.**
+ Args:
+ routes (dict[str, Union[Callable[[], object], Callable[[], Coroutine[None, None, object]], object]]):
+ A dictionary of routes, where the key is the URL path and the value is a function
+ that returns the content to display.
- - An `Html` object.
+ Returns:
+ Html: An Html object.
"""
_name: Final[str] = "marimo-routes"
diff --git a/marimo/_plugins/stateless/sidebar.py b/marimo/_plugins/stateless/sidebar.py
index 9c1996370b..5973deae9d 100644
--- a/marimo/_plugins/stateless/sidebar.py
+++ b/marimo/_plugins/stateless/sidebar.py
@@ -13,10 +13,10 @@ from marimo._plugins.stateless.flex import vstack
@mddoc
class sidebar(Html):
- """
- Displays content in a sidebar. This is a special layout component that
- will display the content in a sidebar layout, rather than below/above
- the cell.
+ """Displays content in a sidebar.
+
+ This is a special layout component that will display the content in a sidebar
+ layout, rather than below/above the cell.
This component still needs to be the last expression in the cell,
in order to display correctly.
@@ -24,36 +24,33 @@ class sidebar(Html):
You may use more than one `mo.sidebar` - they will be displayed in the
order they are called.
- **Examples.**
-
- ```python
- mo.sidebar(
- [
- mo.md("# marimo"),
- mo.nav_menu(
- {
- "#home": f"{mo.icon('lucide:home')} Home",
- "#about": f"{mo.icon('lucide:user')} About",
- "#contact": f"{mo.icon('lucide:phone')} Contact",
- "Links": {
- "https://twitter.com/marimo_io": "Twitter",
- "https://github.com/marimo-team/marimo": "GitHub",
+ Examples:
+ ```python
+ mo.sidebar(
+ [
+ mo.md("# marimo"),
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ "Links": {
+ "https://twitter.com/marimo_io": "Twitter",
+ "https://github.com/marimo-team/marimo": "GitHub",
+ },
},
- },
- orientation="vertical",
- ),
- ]
- )
- ```
-
- **Args.**
-
- - `item`: the content to display in the sidebar
- - `footer`: the content to display at the bottom of the sidebar
+ orientation="vertical",
+ ),
+ ]
+ )
+ ```
- **Returns.**
+ Args:
+ item (object): The content to display in the sidebar.
+ footer (object, optional): The content to display at the bottom of the sidebar.
- - An `Html` object.
+ Returns:
+ Html: An Html object.
"""
def __init__(self, item: object, footer: Optional[object] = None) -> None:
diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.py
index dc11bcb020..5613e464a4 100644
--- a/marimo/_plugins/stateless/status/_progress.py
+++ b/marimo/_plugins/stateless/status/_progress.py
@@ -61,21 +61,23 @@ class _Progress(Html):
) -> None:
"""Update the progress indicator.
- **Example.**
-
- ```python
- # Increment by 1
- progress.update()
-
- # Increment by 10 and update title and subtitle
- progress.update(10, title="Loading", subtitle="Still going...")
- ```
-
- **Args.**
-
- - increment: amount to increment by. Defaults to 1.
- - title: new title. Defaults to None.
- - subtitle: new subtitle. Defaults to None.
+ Examples:
+ Increment by 1:
+ ```python
+ # Increment by 1
+ progress.update()
+ ```
+
+ Increment by 10 and update title and subtitle:
+ ```python
+ # Increment by 10 and update title and subtitle
+ progress.update(10, title="Loading", subtitle="Still going...")
+ ```
+
+ Args:
+ increment (int, optional): Amount to increment by. Defaults to 1.
+ title (str, optional): New title. Defaults to None.
+ subtitle (str, optional): New subtitle. Defaults to None.
"""
if self.closed:
raise RuntimeError(
@@ -93,7 +95,7 @@ class _Progress(Html):
@debounce(0.15)
def debounced_flush(self) -> None:
- """Flush the output to the UI"""
+ """Flush the output to the UI."""
output.flush()
def clear(self) -> None:
@@ -194,53 +196,54 @@ class Spinner(_Progress):
def update(
self, title: str | None = None, subtitle: str | None = None
) -> None:
- """Update the title and subtitle of the spinner
+ """Update the title and subtitle of the spinner.
This method updates a spinner output in-place. Must be used
in the cell the spinner was created.
- **Example.**
-
- ```python
- with mo.status.spinner("Hang tight!") as _spinner:
- ...
- _spinner.update(title="Almost done!")
- # Optionally, remove the spinner from the output
- # _spinner.clear()
- ```
+ Examples:
+ ```python
+ with mo.status.spinner("Hang tight!") as _spinner:
+ ...
+ _spinner.update(title="Almost done!")
+ # Optionally, remove the spinner from the output
+ # _spinner.clear()
+ ```
+
+ Args:
+ title (str, optional): New title. Defaults to None.
+ subtitle (str, optional): New subtitle. Defaults to None.
"""
super().update_progress(increment=1, title=title, subtitle=subtitle)
@mddoc
class spinner:
- """Show a loading spinner
+ """Show a loading spinner.
Use `mo.status.spinner()` as a context manager to show a loading spinner.
You can optionally pass a title and subtitle.
- **Example.**
-
- ```python
- with mo.status.spinner(subtitle="Loading data ...") as _spinner:
- data = expensive_function()
- _spinner.update(subtitle="Crunching numbers ...")
- ...
-
- mo.ui.table(data)
- ```
-
- You can also show the spinner without a context manager:
+ Examples:
+ ```python
+ with mo.status.spinner(subtitle="Loading data ...") as _spinner:
+ data = expensive_function()
+ _spinner.update(subtitle="Crunching numbers ...")
+ ...
- ```python
- mo.status.spinner(title="Loading ...") if condition else mo.md("Done!")
- ```
+ mo.ui.table(data)
+ ```
- **Args:**
+ You can also show the spinner without a context manager:
+ ```python
+ mo.status.spinner(title="Loading ...") if condition else mo.md("Done!")
+ ```
- - `title`: optional title
- - `subtitle`: optional subtitle
- - `remove_on_exit`: if True, the spinner is removed from output on exit
+ Args:
+ title (str, optional): Optional title.
+ subtitle (str, optional): Optional subtitle.
+ remove_on_exit (bool, optional): If True, the spinner is removed from output on exit.
+ Defaults to True.
"""
def __init__(
@@ -269,47 +272,41 @@ class spinner:
class progress_bar:
- """Iterate over a collection and show a progress bar
-
- **Example.**
-
- ```python
- for i in mo.status.progress_bar(range(10)):
- ...
- ```
+ """Iterate over a collection and show a progress bar.
- You can optionally provide a title and subtitle to show
- during iteration, and a title/subtitle to show upon completion.
+ Examples:
+ ```python
+ for i in mo.status.progress_bar(range(10)):
+ ...
+ ```
- You can also use progress_bar with a context manager and manually update
- the bar:
+ You can optionally provide a title and subtitle to show
+ during iteration, and a title/subtitle to show upon completion:
+ ```python
+ with mo.status.progress_bar(total=10) as bar:
+ for i in range(10):
+ ...
+ bar.update()
+ ```
- ```python
- with mo.status.progress_bar(total=10) as bar:
- for i in range(10):
- ...
- bar.update()
- ```
-
- The `update` method accepts the optional keyword
- arguments `increment` (defaults to `1`), `title`,
- and `subtitle`.
-
- For performance reasons, the progress bar is only updated in the UI
- every 150ms.
-
- **Args.**
-
- - `collection`: optional collection to iterate over
- - `title`: optional title
- - `subtitle`: optional subtitle
- - `completion_title`: optional title to show during completion
- - `completion_subtitle`: optional subtitle to show during completion
- - `total`: optional total number of items to iterate over
- - `show_rate`: if True, show the rate of progress (items per second)
- - `show_eta`: if True, show the estimated time of completion
- - `remove_on_exit`: if True, remove the progress bar from output on exit
- - `disabled`: if True, disable the progress bar
+ The `update` method accepts the optional keyword
+ arguments `increment` (defaults to `1`), `title`,
+ and `subtitle`.
+
+ For performance reasons, the progress bar is only updated in the UI
+ every 150ms.
+
+ Args:
+ collection (Collection[Union[S, int]], optional): Optional collection to iterate over.
+ title (str, optional): Optional title.
+ subtitle (str, optional): Optional subtitle.
+ completion_title (str, optional): Optional title to show during completion.
+ completion_subtitle (str, optional): Optional subtitle to show during completion.
+ total (int, optional): Optional total number of items to iterate over.
+ show_rate (bool, optional): If True, show the rate of progress (items per second).
+ show_eta (bool, optional): If True, show the estimated time of completion.
+ remove_on_exit (bool, optional): If True, remove the progress bar from output on exit.
+ disabled (bool, optional): If True, disable the progress bar.
"""
def __init__(
@@ -390,23 +387,23 @@ def toast(
description: str = "",
kind: Optional[Literal["danger"]] = None,
) -> None:
- """Show a toast notification
+ """Show a toast notification.
Use `mo.status.toast()` to display a brief notification.
- **Example.**
-
- ```python
- mo.status.toast(
- "Operation completed",
- "Your task has finished successfully",
- )
- ```
-
- **Args:**
+ Examples:
+ ```python
+ mo.status.toast(
+ "Operation completed",
+ "Your task has finished successfully",
+ )
+ ```
- - `title`: The main message of the toast
- - `description`: Optional additional details (can include HTML)
- - `kind`: Optional kind, use "danger" for error toasts
+ Args:
+ title (str): The main message of the toast.
+ description (str, optional): Optional additional details (can include HTML).
+ Defaults to "".
+ kind (Literal["danger"], optional): Optional kind, use "danger" for error toasts.
+ Defaults to None.
"""
Alert(title=title, description=description, variant=kind).broadcast()
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 8f6da1d8ae..4b459f5318 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -223,58 +223,56 @@ def _has_transforms(spec: VegaSpec) -> bool:
@mddoc
class altair_chart(UIElement[ChartSelection, ChartDataType]):
- """Make reactive charts with Altair
+ """Make reactive charts with Altair.
Use `mo.ui.altair_chart` to make Altair charts reactive: select chart data
with your cursor on the frontend, get them as a dataframe in Python!
Supports polars, pandas, and arrow DataFrames.
- **Example.**
+ Examples:
+ ```python
+ import altair as alt
+ import marimo as mo
+ from vega_datasets import data
- ```python
- import altair as alt
- import marimo as mo
- from vega_datasets import data
-
- chart = (
- alt.Chart(data.cars())
- .mark_point()
- .encode(
- x="Horsepower",
- y="Miles_per_Gallon",
- color="Origin",
+ chart = (
+ alt.Chart(data.cars())
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin",
+ )
)
- )
-
- chart = mo.ui.altair_chart(chart)
- ```
-
- ```
- # View the chart and selected data as a dataframe
- mo.hstack([chart, chart.value])
- ```
-
- **Attributes.**
-
- - `value`: a dataframe of the plot data filtered by the selections
- - `dataframe`: a dataframe of the unfiltered chart data
- - `selections`: the selection of the chart; this may be an interval along
- the name of an axis or a selection of points
-
- **Initialization Args.**
-
- - `chart`: An `altair.Chart`
- - `chart_selection`: optional selection type,
- `"point"`, `"interval"`, or a bool; defaults to `True` which will
- automatically detect the best selection type.
- This is ignored if the chart already has a point/interval selection param.
- - `legend_selection`: optional list of legend fields (columns) for which to
- enable selection, `True` to enable selection for all fields, or
- `False` to disable selection entirely.
- This is ignored if the chart already has a legend selection param.
- - `label`: optional markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+
+ chart = mo.ui.altair_chart(chart)
+ ```
+
+ ```python
+ # View the chart and selected data as a dataframe
+ mo.hstack([chart, chart.value])
+ ```
+
+ Attributes:
+ value (ChartDataType): A dataframe of the plot data filtered by the selections.
+ dataframe (ChartDataType): A dataframe of the unfiltered chart data.
+ selections (ChartSelection): The selection of the chart; this may be an interval
+ along the name of an axis or a selection of points.
+
+ Args:
+ chart (altair.Chart): An Altair Chart object.
+ chart_selection (Union[Literal["point"], Literal["interval"], bool], optional):
+ Selection type, "point", "interval", or a bool. Defaults to True which will
+ automatically detect the best selection type. This is ignored if the chart
+ already has a point/interval selection param.
+ legend_selection (Union[list[str], bool], optional): List of legend fields
+ (columns) for which to enable selection, True to enable selection for all
+ fields, or False to disable selection entirely. This is ignored if the chart
+ already has a legend selection param. Defaults to True.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Optional[Callable[[ChartDataType], None]], optional): Optional
+ callback to run when this element's value changes. Defaults to None.
"""
name: Final[str] = "marimo-vega"
@@ -472,39 +470,36 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
This method is useful when you have a layered chart and you want to
apply the selection to a DataFrame.
- **Example.**
+ Args:
+ df (ChartDataType): A DataFrame to apply the selection to.
- ```python
- import altair as alt
- import marimo as mo
- from vega_datasets import data
+ Returns:
+ ChartDataType: A DataFrame of the plot data filtered by the selections.
- cars = data.cars()
+ Examples:
+ ```python
+ import altair as alt
+ import marimo as mo
+ from vega_datasets import data
- _chart = (
- alt.Chart(cars)
- .mark_point()
- .encode(
- x="Horsepower",
- y="Miles_per_Gallon",
- color="Origin",
- )
- )
-
- chart = mo.ui.altair_chart(_chart)
- chart
-
- # In another cell
- selected_df = chart.apply_selection(cars)
- ```
-
- **Args.**
+ cars = data.cars()
- - `df`: a DataFrame to apply the selection to
+ _chart = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin",
+ )
+ )
- **Returns.**
+ chart = mo.ui.altair_chart(_chart)
+ chart
- - a DataFrame of the plot data filtered by the selections
+ # In another cell
+ selected_df = chart.apply_selection(cars)
+ ```
"""
assert assert_can_narwhalify(df)
return _filter_dataframe(df, self.selections)
diff --git a/marimo/_plugins/ui/_impl/array.py b/marimo/_plugins/ui/_impl/array.py
index b673e6e784..db6c4c0616 100644
--- a/marimo/_plugins/ui/_impl/array.py
+++ b/marimo/_plugins/ui/_impl/array.py
@@ -16,11 +16,9 @@ from marimo._plugins.ui._core.ui_element import UIElement
# Python type is a sequence of values, one for each UI element
@mddoc
class array(UIElement[Dict[str, JSONType], Sequence[object]]):
- """
- An array of UI elements.
-
- Use an array to
+ """An array of UI elements.
+ Use an array to:
- create a dynamic number of UI elements at runtime
- group together logically related UI elements
- keep the number of global variables in your program small
@@ -37,44 +35,42 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):
interacting with the array will _not_ update the original elements, and
vice versa.
- **Examples.**
-
- A heterogeneous collection of UI elements:
-
- ```python
- array = mo.ui.array([mo.ui.slider(1, 10), mo.ui.text(), mo.ui.date()])
- ```
-
- Get the values of the `slider`, `text`, and `date` elements via
- `array.value`:
+ Examples:
+ A heterogeneous collection of UI elements:
- ```python
- # array.value returns a list with the values of the elements
- array.value
- ```
+ ```python
+ array = mo.ui.array([mo.ui.slider(1, 10), mo.ui.text(), mo.ui.date()])
+ ```
- Access and output a UI element in the array:
+ Get the values of the `slider`, `text`, and `date` elements via
+ `array.value`:
- ```python
- mo.md(f"This is a slider: array[0]")
- ```
+ ```python
+ # array.value returns a list with the values of the elements
+ array.value
+ ```
- Some number of UI elements, determined at runtime:
+ Access and output a UI element in the array:
- ```python
- mo.ui.array([mo.ui.slider(1, 10) for _ in range random.randint(4, 8)])
- ```
+ ```python
+ mo.md(f"This is a slider: array[0]")
+ ```
- **Attributes.**
+ Some number of UI elements, determined at runtime:
- - `value`: a list containing the values of the array's entries
- - `elements`: a list of the wrapped elements (clones of the originals)
+ ```python
+ mo.ui.array([mo.ui.slider(1, 10) for _ in range random.randint(4, 8)])
+ ```
- **Initialization Args.**
+ Attributes:
+ value (list): A list containing the values of the array's entries.
+ elements (list): A list of the wrapped elements (clones of the originals).
- - `elements`: the UI elements to include
- - `label`: a descriptive name for the array
- - `on_change`: optional callback to run when this element's value changes
+ Args:
+ elements (Sequence[UIElement]): The UI elements to include.
+ label (str, optional): A descriptive name for the array. Defaults to "".
+ on_change (Optional[Callable[[Sequence[object]], None]], optional): Optional callback
+ to run when this element's value changes.
"""
_name: Final[str] = "marimo-dict"
@@ -155,17 +151,23 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):
return item in self.elements
def hstack(self, **kwargs: Any) -> Html:
- """
- Stack the elements horizontally.
+ """Stack the elements horizontally.
+
+ Args:
+ **kwargs: Additional arguments passed to `marimo.hstack`.
- For kwargs, see `marimo.hstack`.
+ Returns:
+ Html: HTML representation of horizontally stacked elements.
"""
return hstack(items=self.elements, **kwargs)
def vstack(self, **kwargs: Any) -> Html:
- """
- Stack the elements vertically.
+ """Stack the elements vertically.
+
+ Args:
+ **kwargs: Additional arguments passed to `marimo.vstack`.
- For kwargs, see `marimo.vstack`.
+ Returns:
+ Html: HTML representation of vertically stacked elements.
"""
return vstack(items=self.elements, **kwargs)
diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.py
index ec99bfb247..ed99d10672 100644
--- a/marimo/_plugins/ui/_impl/batch.py
+++ b/marimo/_plugins/ui/_impl/batch.py
@@ -23,9 +23,7 @@ if TYPE_CHECKING:
# - Frontend type is a dict {label => value update}
# - Python type is a dict mapping label -> value
class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):
- """
- A batch of named UI elements represented by HTML text.
- """
+ """A batch of named UI elements represented by HTML text."""
_name: Final[str] = "marimo-dict"
@@ -76,12 +74,31 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):
return item in self.elements
def get(self, key: str, default: Any | None = None) -> Any:
+ """Get a UI element by key with an optional default value.
+
+ Args:
+ key (str): The key to look up in the batch.
+ default (Any | None, optional): Value to return if key is not found. Defaults to None.
+
+ Returns:
+ Any: The UI element if found, otherwise the default value.
+ """
return self.elements.get(key, default)
def items(self) -> ItemsView[str, UIElement[JSONType, object]]:
+ """Return a view of the batch's items (key-value pairs).
+
+ Returns:
+ ItemsView[str, UIElement]: A view of the batch's (key, element) pairs.
+ """
return self.elements.items()
def values(self) -> ValuesView[UIElement[JSONType, object]]:
+ """Return a view of the batch's values (UI elements).
+
+ Returns:
+ ValuesView[UIElement]: A view of the batch's UI elements.
+ """
return self.elements.values()
def _convert_value(self, value: dict[str, JSONType]) -> dict[str, object]:
@@ -111,8 +128,7 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):
@mddoc
class batch(_batch_base):
- """
- Convert an HTML object with templated text into a UI element.
+ """Convert an HTML object with templated text into a UI element.
A `batch` is a UI element that wraps other UI elements, and is
represented by custom HTML or markdown. You can create
@@ -121,53 +137,50 @@ class batch(_batch_base):
Get the value of the wrapped UI elements using the `value` attribute
of the batch.
- **Example.**
-
- In the below example, `user_info` is a UI Element whose output is markdown
- and whose value is a dict with keys `'name'` and `'birthday'`
- (and values equal to the values of their corresponding elements).
-
-
- ```python3
- user_info = mo.md(
- '''
- - What's your name?: {name}
- - When were you born?: {birthday}
- '''
- ).batch(name=mo.ui.text(), birthday=mo.ui.date())
- ```
-
- To get the value of `name` and `birthday`, use:
-
- ```
- user_info.value
- ```
-
- You can also instantiate this class directly:
-
- ```python3
- markdown = mo.md(
- '''
- - What's your name?: {name}
- - When were you born?: {birthday}
- '''
- )
- batch = mo.ui.batch(
- markdown, {"name": mo.ui.text(), "birthday": mo.ui.date()}
- )
- ```
-
- **Attributes.**
-
- - `value`: a `dict` of the batched elements' values
- - `elements`: a `dict` of the batched elements (clones of the originals)
- - `on_change`: optional callback to run when this element's value changes
-
- **Initialization Args.**
-
- - html: a templated `Html` object
- - elements: the UI elements to interpolate into the HTML template
- - `on_change`: optional callback to run when this element's value changes
+ Examples:
+ In the below example, `user_info` is a UI Element whose output is markdown
+ and whose value is a dict with keys `'name'` and `'birthday'`
+ (and values equal to the values of their corresponding elements).
+
+ ```python3
+ user_info = mo.md(
+ '''
+ - What's your name?: {name}
+ - When were you born?: {birthday}
+ '''
+ ).batch(name=mo.ui.text(), birthday=mo.ui.date())
+ ```
+
+ To get the value of `name` and `birthday`, use:
+
+ ```
+ user_info.value
+ ```
+
+ You can also instantiate this class directly:
+
+ ```python3
+ markdown = mo.md(
+ '''
+ - What's your name?: {name}
+ - When were you born?: {birthday}
+ '''
+ )
+ batch = mo.ui.batch(
+ markdown, {"name": mo.ui.text(), "birthday": mo.ui.date()}
+ )
+ ```
+
+ Attributes:
+ value (dict): A dict of the batched elements' values.
+ elements (dict): A dict of the batched elements (clones of the originals).
+ on_change (Optional[Callable]): Optional callback to run when this element's value changes.
+
+ Args:
+ html (Html): A templated Html object.
+ elements (dict[str, UIElement]): The UI elements to interpolate into the HTML template.
+ on_change (Optional[Callable[[Dict[str, object]], None]], optional): Optional callback
+ to run when this element's value changes.
"""
def __init__(
diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.py
index 763bd25b8e..3cbcefc906 100644
--- a/marimo/_plugins/ui/_impl/chat/chat.py
+++ b/marimo/_plugins/ui/_impl/chat/chat.py
@@ -35,98 +35,92 @@ class GetChatHistoryResponse:
@mddoc
class chat(UIElement[Dict[str, Any], List[ChatMessage]]):
- """
- A chatbot UI element for interactive conversations.
-
- **Example: Using a custom model.**
-
- Define a chatbot by implementing a function that takes a list of
- `ChatMessage`s and optionally a config object as input, and returns the
- chat response. The response can be any object, including text, plots, or
- marimo UI elements.
-
- ```python
- def my_rag_model(messages, config):
- # Each message has a `content` attribute, as well as a `role`
- # attribute ("user", "system", "assistant");
- question = messages[-1].content
- docs = find_docs(question)
- prompt = template(question, docs, messages)
- response = query(prompt)
- if is_dataset(response):
- return dataset_to_chart(response)
- return response
-
-
- chat = mo.ui.chat(my_rag_model)
- ```
-
- Async functions and async generators are also supported, meaning these
- are both valid chat functions:
-
- ```python
- async def my_rag_model(messages):
- return await my_async_function(messages)
- ```
-
- ```python
- async def my_rag_model(messages):
- for response in my_async_iterator(messages):
- yield response
- ```
-
- The last value yielded by the async generator is treated as the model
- response. ui.chat does not yet support streaming responses to the frontend.
- Please file a GitHub issue if this is important to you:
- https://github.com/marimo-team/marimo/issues
-
- **Example: Using a built-in model.**
-
- Instead of defining a chatbot function, you can use a built-in model from
- the `mo.ai.llm` module.
-
- ```python
- chat = mo.ui.chat(
- mo.ai.llm.openai(
- "gpt-4o",
- system_message="You are a helpful assistant.",
- ),
- )
- ```
-
- You can also allow the user to include attachments in their messages.
-
- ```python
- chat = mo.ui.chat(
- mo.ai.llm.openai(
- "gpt-4o",
- ),
- allow_attachments=["image/png", "image/jpeg"],
- )
- ```
-
- **Attributes.**
-
- - `value`: the current chat history, a list of `ChatMessage` objects.
-
- **Initialization Args.**
-
- - `model`: `(Callable[[List[ChatMessage], ChatModelConfig], object])` a
- callable that takes in the chat history and returns a response
- - `prompts`: optional list of initial prompts to present to the user
- - `on_message`: optional callback function to handle new messages
- - `show_configuration_controls`: whether to show the configuration controls
- - `config`: optional `ChatModelConfigDict` to override the default
- configuration. Keys include:
- - `max_tokens`
- - `temperature`
- - `top_p`
- - `top_k`
- - `frequency_penalty`
- - `presence_penalty`
- - `allow_attachments`: (bool | List[str]) allow attachments. True for any
- attachments types, or pass a list of mime types
- - `max_height`: optional maximum height for the chat element
+ """A chatbot UI element for interactive conversations.
+
+ Define a chatbot by implementing a function that takes a list of ChatMessages and
+ optionally a config object as input, and returns the chat response. The response
+ can be any object, including text, plots, or marimo UI elements.
+
+ Examples:
+ Using a custom model:
+ ```python
+ def my_rag_model(messages, config):
+ # Each message has a `content` attribute, as well as a `role`
+ # attribute ("user", "system", "assistant");
+ question = messages[-1].content
+ docs = find_docs(question)
+ prompt = template(question, docs, messages)
+ response = query(prompt)
+ if is_dataset(response):
+ return dataset_to_chart(response)
+ return response
+
+
+ chat = mo.ui.chat(my_rag_model)
+ ```
+
+ Async functions and async generators are also supported:
+ ```python
+ async def my_rag_model(messages):
+ return await my_async_function(messages)
+ ```
+
+ ```python
+ async def my_rag_model(messages):
+ for response in my_async_iterator(messages):
+ yield response
+ ```
+
+ The last value yielded by the async generator is treated as the model
+ response. ui.chat does not yet support streaming responses to the frontend.
+ Please file a GitHub issue if this is important to you:
+ https://github.com/marimo-team/marimo/issues
+
+ Using a built-in model:
+ ```python
+ chat = mo.ui.chat(
+ mo.ai.llm.openai(
+ "gpt-4o",
+ system_message="You are a helpful assistant.",
+ ),
+ )
+ ```
+
+ Using attachments:
+ ```python
+ chat = mo.ui.chat(
+ mo.ai.llm.openai(
+ "gpt-4o",
+ ),
+ allow_attachments=["image/png", "image/jpeg"],
+ )
+ ```
+
+ Attributes:
+ value (List[ChatMessage]): The current chat history, a list of ChatMessage objects.
+
+ Args:
+ model (Callable[[List[ChatMessage], ChatModelConfig], object]): A callable that
+ takes in the chat history and returns a response.
+ prompts (List[str], optional): Optional list of initial prompts to present to
+ the user. Defaults to None.
+ on_message (Callable[[List[ChatMessage]], None], optional): Optional callback
+ function to handle new messages. Defaults to None.
+ show_configuration_controls (bool, optional): Whether to show the configuration
+ controls. Defaults to False.
+ config (ChatModelConfigDict, optional): Optional configuration to override the
+ default configuration. Keys include:
+ - max_tokens
+ - temperature
+ - top_p
+ - top_k
+ - frequency_penalty
+ - presence_penalty
+ Defaults to None.
+ allow_attachments (bool | List[str], optional): Allow attachments. True for any
+ attachments types, or pass a list of mime types. Defaults to False.
+ max_height (int, optional): Optional maximum height for the chat element.
+ Defaults to None.
"""
_name: Final[str] = "marimo-chatbot"
diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.py
index 5a4e462c97..e2ffe62945 100644
--- a/marimo/_plugins/ui/_impl/data_editor.py
+++ b/marimo/_plugins/ui/_impl/data_editor.py
@@ -34,17 +34,36 @@ if TYPE_CHECKING:
@dataclass
class DataEditorValue:
- # Row-oriented data
+ """A dataclass representing the value of a data editor.
+
+ Attributes:
+ data (List[Dict[str, Any]]): Row-oriented data as a list of dictionaries.
+ """
+
data: List[Dict[str, Any]]
class PositionalEdit(TypedDict):
+ """A typed dictionary representing a single edit in the data editor.
+
+ Attributes:
+ rowIdx (int): The index of the row being edited.
+ columnId (str): The ID of the column being edited.
+ value (Any): The new value for the cell.
+ """
+
rowIdx: int
columnId: str
value: Any
class DataEdits(TypedDict):
+ """A typed dictionary containing a list of positional edits.
+
+ Attributes:
+ edits (List[PositionalEdit]): List of individual cell edits.
+ """
+
edits: List[PositionalEdit]
@@ -59,56 +78,50 @@ class data_editor(
Union[RowOrientedData, ColumnOrientedData, IntoDataFrame],
]
):
- """
- **[EXPERIMENTAL]**
+ """[EXPERIMENTAL] A data editor component for editing tabular data.
This component is experimental and intentionally limited in features,
if you have any feature requests, please file an issue at
https://github.com/marimo-team/marimo/issues.
- A data editor component for editing tabular data.
-
The data can be supplied as:
1. a Pandas, Polars, or Pyarrow DataFrame
2. a list of dicts, with one dict for each row, keyed by column names
3. a dict of lists, with each list representing a column
- **Examples.**
-
- Create a data editor from a Pandas dataframe:
-
- ```python
- import pandas as pd
-
- df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
- editor = mo.ui.experimental_data_editor(data=df, label="Edit Data")
- ```
+ Examples:
+ Create a data editor from a Pandas dataframe:
- Create a data editor from a list of dicts:
+ ```python
+ import pandas as pd
- ```python
- data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
- editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
- ```
+ df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ editor = mo.ui.experimental_data_editor(data=df, label="Edit Data")
+ ```
- Create a data editor from a dict of lists:
+ Create a data editor from a list of dicts:
- ```python
- data = {"A": [1, 2, 3], "B": ["a", "b", "c"]}
- editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
- ```
+ ```python
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "a"}, {"A": 3, "B": "c"}]
+ editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
+ ```
- **Attributes.**
+ Create a data editor from a dict of lists:
- - `value`: the current state of the edited data
- - `data`: the original data passed to the editor
+ ```python
+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"]}
+ editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
+ ```
- **Initialization Args.**
+ Attributes:
+ value (Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]): The current state of the edited data.
+ data (Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]): The original data passed to the editor.
- - `data`: The data to be edited. Can be a Pandas dataframe,
- a list of dicts, or a dict of lists.
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Args:
+ data (Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]): The data to be edited.
+ Can be a Pandas dataframe, a list of dicts, or a dict of lists.
+ label (str): Markdown label for the element.
+ on_change (Optional[Callable]): Optional callback to run when this element's value changes.
"""
_name: Final[str] = "marimo-data-editor"
diff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.py
index f25bed5742..1465e52141 100644
--- a/marimo/_plugins/ui/_impl/data_explorer.py
+++ b/marimo/_plugins/ui/_impl/data_explorer.py
@@ -15,22 +15,18 @@ if TYPE_CHECKING:
@mddoc
class data_explorer(UIElement[Dict[str, Any], Dict[str, Any]]):
- """
- Quickly explore a DataFrame with automatically suggested visualizations.
-
- **Example.**
-
- ```python
- mo.ui.data_explorer(data)
- ```
-
- **Attributes.**
+ """Quickly explore a DataFrame with automatically suggested visualizations.
- - `value`: the resulting DataFrame chart spec
+ Examples:
+ ```python
+ mo.ui.data_explorer(data)
+ ```
- **Initialization Args.**
+ Attributes:
+ value (Dict[str, Any]): The resulting DataFrame chart spec.
- - `df`: the DataFrame to visualize
+ Args:
+ df (IntoDataFrame): The DataFrame to visualize.
"""
_name: Final[str] = "marimo-data-explorer"
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 6e49881b34..5841711e34 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -79,27 +79,27 @@ class GetDataFrameError(Exception):
@mddoc
class dataframe(UIElement[Dict[str, Any], DataFrameType]):
- """
- Run transformations on a DataFrame or series.
- Currently only Pandas or Polars DataFrames are supported.
-
- **Example.**
-
- ```python
- dataframe = mo.ui.dataframe(data)
- ```
+ """Run transformations on a DataFrame or series.
- **Attributes.**
-
- - `value`: the transformed DataFrame or series
-
- **Initialization Args.**
+ Currently only Pandas or Polars DataFrames are supported.
- - `df`: the DataFrame or series to transform
- - `page_size`: the number of rows to show in the table
- - `limit`: the number of items to load into memory, in case
- the data is remote and lazily fetched. This is likely true
- for SQL-backed dataframes via Ibis.
+ Examples:
+ ```python
+ dataframe = mo.ui.dataframe(data)
+ ```
+
+ Attributes:
+ value (DataFrameType): The transformed DataFrame or series.
+
+ Args:
+ df (DataFrameType): The DataFrame or series to transform.
+ page_size (Optional[int], optional): The number of rows to show in the table.
+ Defaults to 5.
+ limit (Optional[int], optional): The number of items to load into memory, in case
+ the data is remote and lazily fetched. This is likely true for SQL-backed
+ dataframes via Ibis.
+ on_change (Optional[Callable[[DataFrameType], None]], optional): Optional callback
+ to run when this element's value changes.
"""
_name: Final[str] = "marimo-dataframe"
diff --git a/marimo/_plugins/ui/_impl/dates.py b/marimo/_plugins/ui/_impl/dates.py
index 9e7bddecc3..6e1648b4d0 100644
--- a/marimo/_plugins/ui/_impl/dates.py
+++ b/marimo/_plugins/ui/_impl/dates.py
@@ -28,55 +28,49 @@ Numeric = Union[int, float]
@mddoc
class date(UIElement[str, dt.date]):
- """
- A date picker with an optional start and stop date.
-
- **Example.**
-
- ```python
- # initialize the date picker at a given date
- date = mo.ui.date(value="2022-01-01")
- ```
-
- ```python
- # when value is omitted, date picker initializes with today's date
- date = mo.ui.date()
- ```
-
- ```python
- # create a date picker with bounds
- date = mo.ui.date(
- value="2022-06-01",
- start="2022-01-01",
- stop="2022-12-31",
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- date = mo.ui.date.from_series(df["column_name"])
- ```
-
- **Attributes.**
-
- - `value`: a str (YYYY-MM-DD) or `datetime.date` object of the chosen date
- - `start`: the start date
- - `stop`: the stop date
-
- **Initialization Args.**
-
- - `start`: minimum date selectable; if None, defaults to 01-01-0001
- - `stop`: maximum date selectable; if None, defaults to 12-31-9999
- - `value`: default date
- - if `None` and `start` and `stop` are `None`, defaults to the
- current day;
- - else if `None` and `start` is not `None`, defaults to `start`;
- - else if `None` and `stop` is not `None`, defaults to `stop`
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
+ """A date picker with an optional start and stop date.
+
+ Examples:
+ ```python
+ # initialize the date picker at a given date
+ date = mo.ui.date(value="2022-01-01")
+ ```
+
+ ```python
+ # when value is omitted, date picker initializes with today's date
+ date = mo.ui.date()
+ ```
+
+ ```python
+ # create a date picker with bounds
+ date = mo.ui.date(
+ value="2022-06-01",
+ start="2022-01-01",
+ stop="2022-12-31",
+ )
+ ```
+
+ Or from a dataframe series:
+
+ ```python
+ date = mo.ui.date.from_series(df["column_name"])
+ ```
+
+ Attributes:
+ value (str | datetime.date): A str (YYYY-MM-DD) or `datetime.date` object of the chosen date.
+ start (datetime.date): The start date.
+ stop (datetime.date): The stop date.
+
+ Args:
+ start (datetime.date | str, optional): Minimum date selectable. If None, defaults to 01-01-0001.
+ stop (datetime.date | str, optional): Maximum date selectable. If None, defaults to 12-31-9999.
+ value (datetime.date | str, optional): Default date.
+ If None and start and stop are None, defaults to the current day.
+ If None and start is not None, defaults to start.
+ If None and stop is not None, defaults to stop.
+ label (str, optional): Markdown label for the element.
+ on_change (Callable[[datetime.date], None], optional): Optional callback to run when this element's value changes.
+ full_width (bool, optional): Whether the input should take up the full width of its container.
"""
_name: Final[str] = "marimo-date"
@@ -138,7 +132,16 @@ class date(UIElement[str, dt.date]):
@staticmethod
def from_series(series: DataFrameSeries, **kwargs: Any) -> "date":
- """Create a date picker from a dataframe series."""
+ """Create a date picker from a dataframe series.
+
+ Args:
+ series (DataFrameSeries): A pandas Series containing datetime values.
+ **kwargs: Additional keyword arguments passed to the date picker constructor.
+ Supported arguments: start, stop, label, and any other date picker parameters.
+
+ Returns:
+ date: A date picker initialized with the series' min and max dates as bounds.
+ """
info = get_date_series_info(series)
start = kwargs.pop("start", info.min)
stop = kwargs.pop("stop", info.max)
@@ -155,48 +158,55 @@ class date(UIElement[str, dt.date]):
@property
def start(self) -> dt.date:
+ """Get the minimum selectable date.
+
+ Returns:
+ datetime.date: The start date, which is either the user-specified minimum date
+ or 01-01-0001 if no start date was specified.
+ """
return self._start
@property
def stop(self) -> dt.date:
+ """Get the maximum selectable date.
+
+ Returns:
+ datetime.date: The stop date, which is either the user-specified maximum date
+ or 12-31-9999 if no stop date was specified.
+ """
return self._stop
@mddoc
class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
- """
- A datetime picker over an interval.
-
- **Example.**
+ """A datetime picker over an interval.
- ```python
- datetime_picker = mo.ui.datetime(
- start=dt.datetime(2023, 1, 1),
- stop=dt.datetime(2023, 12, 31, 23, 59, 59),
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- datetime_picker = mo.ui.datetime.from_series(df["datetime_column"])
- ```
-
- **Attributes.**
-
- - `value`: the selected datetime, possibly `None`
- - `start`: the minimum selectable datetime
- - `stop`: the maximum selectable datetime
-
- **Initialization Args.**
-
- - `start`: the minimum selectable datetime (default: minimum datetime)
- - `stop`: the maximum selectable datetime (default: maximum datetime)
- - `value`: default value
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of
- its container
+ Examples:
+ ```python
+ datetime_picker = mo.ui.datetime(
+ start=dt.datetime(2023, 1, 1),
+ stop=dt.datetime(2023, 12, 31, 23, 59, 59),
+ )
+ ```
+
+ Or from a dataframe series:
+
+ ```python
+ datetime_picker = mo.ui.datetime.from_series(df["datetime_column"])
+ ```
+
+ Attributes:
+ value (datetime.datetime, optional): The selected datetime, possibly None.
+ start (datetime.datetime): The minimum selectable datetime.
+ stop (datetime.datetime): The maximum selectable datetime.
+
+ Args:
+ start (datetime.datetime | str, optional): The minimum selectable datetime. Defaults to minimum datetime.
+ stop (datetime.datetime | str, optional): The maximum selectable datetime. Defaults to maximum datetime.
+ value (datetime.datetime | str, optional): Default value.
+ label (str, optional): Markdown label for the element.
+ on_change (Callable[[Optional[datetime.datetime]], None], optional): Optional callback to run when this element's value changes.
+ full_width (bool, optional): Whether the input should take up the full width of its container.
"""
_name: Final[str] = "marimo-datetime"
@@ -258,7 +268,16 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
@staticmethod
def from_series(series: DataFrameSeries, **kwargs: Any) -> "datetime":
- """Create a datetime picker from a dataframe series."""
+ """Create a datetime picker from a dataframe series.
+
+ Args:
+ series (DataFrameSeries): A pandas Series containing datetime values.
+ **kwargs: Additional keyword arguments passed to the datetime picker constructor.
+ Supported arguments: start, stop, label, and any other datetime picker parameters.
+
+ Returns:
+ datetime: A datetime picker initialized with the series' min and max datetimes as bounds.
+ """
info = get_datetime_series_info(series)
start = kwargs.pop("start", info.min)
stop = kwargs.pop("stop", info.max)
@@ -285,47 +304,55 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):
@property
def start(self) -> dt.datetime:
+ """Get the minimum selectable datetime.
+
+ Returns:
+ datetime.datetime: The start datetime, which is either the user-specified minimum
+ datetime or datetime.min if no start datetime was specified.
+ """
return self._start
@property
def stop(self) -> dt.datetime:
+ """Get the maximum selectable datetime.
+
+ Returns:
+ datetime.datetime: The stop datetime, which is either the user-specified maximum
+ datetime or datetime.max if no stop datetime was specified.
+ """
return self._stop
@mddoc
class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):
- """
- A date range picker over an interval.
-
- **Example.**
-
- ```python
- date_range = mo.ui.date_range(
- start=dt.date(2023, 1, 1), stop=dt.date(2023, 12, 31)
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- date_range = mo.ui.date_range.from_series(df["date_column"])
- ```
+ """A date range picker over an interval.
- **Attributes.**
-
- - `value`: a tuple of two dates representing the selected range
- - `start`: the minimum selectable date
- - `stop`: the maximum selectable date
-
- **Initialization Args.**
-
- - `start`: the minimum selectable date (default: minimum date)
- - `stop`: the maximum selectable date (default: maximum date)
- - `value`: default value (tuple of two dates)
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
+ Examples:
+ ```python
+ date_range = mo.ui.date_range(
+ start=dt.date(2023, 1, 1), stop=dt.date(2023, 12, 31)
+ )
+ ```
+
+ Or from a dataframe series:
+
+ ```python
+ date_range = mo.ui.date_range.from_series(df["date_column"])
+ ```
+
+ Attributes:
+ value (Tuple[datetime.date, datetime.date]): A tuple of (start_date, end_date) representing the selected range.
+ start (datetime.date): The minimum selectable date.
+ stop (datetime.date): The maximum selectable date.
+
+ Args:
+ start (datetime.date | str, optional): Minimum date selectable. If None, defaults to 01-01-0001.
+ stop (datetime.date | str, optional): Maximum date selectable. If None, defaults to 12-31-9999.
+ value (Tuple[datetime.date | str, datetime.date | str], optional): Default value as (start_date, end_date).
+ If None, defaults to (start, stop) if provided, otherwise today's date for both.
+ label (str, optional): Markdown label for the element.
+ on_change (Callable[[Tuple[datetime.date, datetime.date]], None], optional): Optional callback to run when this element's value changes.
+ full_width (bool, optional): Whether the input should take up the full width of its container.
"""
_name: Final[str] = "marimo-date-range"
@@ -384,7 +411,16 @@ class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):
@staticmethod
def from_series(series: DataFrameSeries, **kwargs: Any) -> "date_range":
- """Create a date range picker from a dataframe series."""
+ """Create a date range picker from a dataframe series.
+
+ Args:
+ series (DataFrameSeries): A pandas Series containing datetime values.
+ **kwargs: Additional keyword arguments passed to the date range picker constructor.
+ Supported arguments: start, stop, label, and any other date range picker parameters.
+
+ Returns:
+ date_range: A date range picker initialized with the series' min and max dates as bounds.
+ """
info = get_date_series_info(series)
start = kwargs.pop("start", info.min)
stop = kwargs.pop("stop", info.max)
@@ -408,8 +444,20 @@ class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):
@property
def start(self) -> dt.date:
+ """Get the minimum selectable date.
+
+ Returns:
+ datetime.date: The start date, which is either the user-specified minimum date
+ or 01-01-0001 if no start date was specified.
+ """
return self._start
@property
def stop(self) -> dt.date:
+ """Get the maximum selectable date.
+
+ Returns:
+ datetime.date: The stop date, which is either the user-specified maximum date
+ or 12-31-9999 if no stop date was specified.
+ """
return self._stop
diff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.py
index ddf7ae1a03..df1e9968c6 100644
--- a/marimo/_plugins/ui/_impl/dictionary.py
+++ b/marimo/_plugins/ui/_impl/dictionary.py
@@ -14,93 +14,83 @@ from marimo._plugins.ui._impl.batch import _batch_base
@mddoc
class dictionary(_batch_base):
- """
- A dictionary of UI elements.
-
- Use a dictionary to
+ """A dictionary of UI elements.
+ Use a dictionary to:
- create a set of UI elements at runtime
- group together logically related UI elements
- keep the number of global variables in your program small
Access the values of the elements using the `value` attribute of the
- dictionary.
-
- The elements in the dictionary can be accessed using square brackets
+ dictionary. The elements in the dictionary can be accessed using square brackets
(`dictionary[key]`) and embedded in other marimo outputs. You can also
iterate over the UI elements using the same syntax used for Python dicts.
- Note: The UI elements in the dictionary are clones of the original
- elements: interacting with the dictionary will _not_ update the original
- elements, and vice versa.
-
- The main reason to use mo.ui.dictionary is for reactive execution — when you
- interact with an element in a mo.ui.dictionary, all cells that reference the
- mo.ui.dictionary run automatically, just like all other ui elements. When you
- use a regular dictionary, you don't get this reactivity.
-
- **Examples.**
-
- A heterogeneous collection of UI elements:
-
- ```python
- d = mo.ui.dictionary(
- {
- "slider": mo.ui.slider(1, 10),
- "text": mo.ui.text(),
- "date": mo.ui.date(),
- }
- )
- ```
-
- Get the values of the `slider`, `text`, and `date` elements via
- `d.value`:
-
- ```python
- # d.value returns a dict with keys "slider", "text", "date"
- d.value
- ```
-
- Access and output a UI element in the array:
-
- ```python
- mo.md(f"This is a slider: {d['slider']}")
- ```
-
- Some number of UI elements, determined at runtime:
-
- ```python
- mo.ui.dictionary(
- {
- f"option {i}": mo.ui.slider(1, 10)
- for i in range(random.randint(4, 8))
- }
- )
- ```
-
- Quick layouts of UI elements:
-
- ```python
- mo.ui.dictionary(
- {
- f"option {i}": mo.ui.slider(1, 10)
- for i in range(random.randint(4, 8))
- }
- ).vstack() # Can also use `hstack`, `callout`, `center`, etc.
- ```
-
- **Attributes.**
-
- - `value`: a dict holding the values of the UI elements, keyed by
- their names.
- - `elements`: a dict of the wrapped elements (clones of the originals)
- - `on_change`: optional callback to run when this element's value changes
-
- **Initialization Args.**
-
- - `elements`: a dict mapping names to UI elements to include
- - `label`: a descriptive name for the dictionary
- to trigger value updates
+ Note:
+ The UI elements in the dictionary are clones of the original
+ elements: interacting with the dictionary will _not_ update the original
+ elements, and vice versa.
+
+ The main reason to use `mo.ui.dictionary` is for reactive execution — when you
+ interact with an element in a `mo.ui.dictionary`, all cells that reference the
+ `mo.ui.dictionary` run automatically, just like all other ui elements. When you
+ use a regular dictionary, you don't get this reactivity.
+
+ Examples:
+ A heterogeneous collection of UI elements:
+ ```python
+ d = mo.ui.dictionary(
+ {
+ "slider": mo.ui.slider(1, 10),
+ "text": mo.ui.text(),
+ "date": mo.ui.date(),
+ }
+ )
+ ```
+
+ Get the values of the `slider`, `text`, and `date` elements via
+ `d.value`:
+ ```python
+ # d.value returns a dict with keys "slider", "text", "date"
+ d.value
+ ```
+
+ Access and output a UI element in the array:
+ ```python
+ mo.md(f"This is a slider: {d['slider']}")
+ ```
+
+ Some number of UI elements, determined at runtime:
+ ```python
+ mo.ui.dictionary(
+ {
+ f"option {i}": mo.ui.slider(1, 10)
+ for i in range(random.randint(4, 8))
+ }
+ )
+ ```
+
+ Quick layouts of UI elements:
+ ```python
+ mo.ui.dictionary(
+ {
+ f"option {i}": mo.ui.slider(1, 10)
+ for i in range(random.randint(4, 8))
+ }
+ ).vstack() # Can also use `hstack`, `callout`, `center`, etc.
+ ```
+
+ Attributes:
+ value (dict): A dict holding the values of the UI elements, keyed by
+ their names.
+ elements (dict): A dict of the wrapped elements (clones of the originals).
+ on_change (Optional[Callable[[dict[str, object]], None]]): Optional callback
+ to run when this element's value changes.
+
+ Args:
+ elements (dict[str, UIElement[Any, Any]]): A dict mapping names to UI
+ elements to include.
+ label (str, optional): A descriptive name for the dictionary. Defaults to "".
"""
def __init__(
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index 92ec291025..a4c34c5946 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -45,36 +45,34 @@ class SendToWidgetArgs:
@mddoc
class anywidget(UIElement[T, T]):
- """
- Create a UIElement from an AnyWidget.
- This proxies all the widget's attributes and methods.
-
- **Example.**
-
- ```python
- from drawdata import ScatterWidget
- import marimo as mo
+ """Create a UIElement from an AnyWidget.
- scatter = ScatterWidget()
- scatter = mo.ui.anywidget(scatter)
+ This proxies all the widget's attributes and methods, allowing seamless
+ integration of AnyWidget instances with Marimo's UI system.
- # In another cell, access its value
- # This works for all widgets
- scatter.value
+ Examples:
+ ```python
+ from drawdata import ScatterWidget
+ import marimo as mo
- # Or attributes specifically on the ScatterWidget
- scatter.data_as_pandas
- scatter.data_as_polars
- ```
+ scatter = ScatterWidget()
+ scatter = mo.ui.anywidget(scatter)
- **Attributes.**
+ # In another cell, access its value
+ # This works for all widgets
+ scatter.value
- - `value`: The value of the widget's traits as a dictionary.
- - `widget`: The widget being wrapped.
+ # Or attributes specifically on the ScatterWidget
+ scatter.data_as_pandas
+ scatter.data_as_polars
+ ```
- **Initialization Args.**
+ Attributes:
+ value (Dict[str, Any]): The value of the widget's traits as a dictionary.
+ widget (AnyWidget): The widget being wrapped.
- - `widget`: The widget to wrap.
+ Args:
+ widget (AnyWidget): The widget to wrap.
"""
def __init__(self, widget: "AnyWidget"):
diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.py
index ea44c3a4ff..245cf1e292 100644
--- a/marimo/_plugins/ui/_impl/from_panel.py
+++ b/marimo/_plugins/ui/_impl/from_panel.py
@@ -185,38 +185,36 @@ def render_component(
@mddoc
class panel(UIElement[T, T]):
- """
- Create a UIElement from a Panel component.
- This proxies all the widget's attributes and methods.
-
- **Example.**
+ """Create a UIElement from a Panel component.
- ```python
- import marimo as mo
- import panel as pn
+ This proxies all the widget's attributes and methods, allowing seamless
+ integration of Panel components with Marimo's UI system.
- slider = pn.widgets.IntSlider(start=0, end=10, value=5)
- rx_stars = mo.ui.panel(slider.rx() * "*")
+ Examples:
+ ```python
+ import marimo as mo
+ import panel as pn
- # In another cell, access its value
- # This works for all widgets
- slider.value
- ```
+ slider = pn.widgets.IntSlider(start=0, end=10, value=5)
+ rx_stars = mo.ui.panel(slider.rx() * "*")
- **Attributes.**
+ # In another cell, access its value
+ # This works for all widgets
+ slider.value
+ ```
- - `obj`: The widget being wrapped.
+ Attributes:
+ obj (Viewable): The widget being wrapped.
- **Initialization Args.**
-
- - `obj`: The widget to wrap.
+ Args:
+ obj (Viewable): The widget to wrap.
"""
def __init__(self, obj: Any):
from panel.models.comm_manager import CommManager as PanelCommManager
from panel.pane import panel as panel_func
- self.obj = obj = panel_func(obj)
+ self.obj: Viewable = panel_func(obj) # type: ignore[assignment]
# This gets set to True in super().__init__()
self._initialized = False
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index 289f8899bf..4f66e75c56 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -568,24 +568,21 @@ def _infer_dtype(
@mddoc
class checkbox(UIElement[bool, bool]):
- """
- A boolean checkbox.
-
- **Example.**
+ """A boolean checkbox.
- ```python
- checkbox = mo.ui.checkbox()
- ```
-
- **Attributes.**
+ Examples:
+ ```python
+ checkbox = mo.ui.checkbox()
+ ```
- - `value`: a boolean, `True` if checked
+ Attributes:
+ value (bool): A boolean, True if checked.
- **Initialization Args.**
-
- - `value`: default value, True or False
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Args:
+ value (bool, optional): Default value, True or False. Defaults to False.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[bool], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
"""
_name: Final[str] = "marimo-checkbox"
@@ -611,43 +608,41 @@ class checkbox(UIElement[bool, bool]):
@mddoc
class radio(UIElement[Optional[str], Any]):
- """
- A radio group.
-
- **Example.**
-
- ```python
- radiogroup = mo.ui.radio(
- options=["a", "b", "c"], value="a", label="choose one"
- )
- ```
-
- ```python
- radiogroup = mo.ui.radio(
- options={"one": 1, "two": 2, "three": 3},
- value="one",
- label="pick a number",
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- radiogroup = mo.ui.radio.from_series(df["column_name"])
- ```
-
- **Attributes.**
-
- - `value`: the value of the selected radio option
- - `options`: a dict mapping option name to option value
+ """A radio group.
- **Initialization Args.**
+ Examples:
+ ```python
+ radiogroup = mo.ui.radio(
+ options=["a", "b", "c"], value="a", label="choose one"
+ )
+ ```
- - `options`: sequence of text options, or dict mapping option name
- to option value
- - `value`: default option name, if None, starts with nothing checked
- - `label`: optional markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ ```python
+ radiogroup = mo.ui.radio(
+ options={"one": 1, "two": 2, "three": 3},
+ value="one",
+ label="pick a number",
+ )
+ ```
+
+ Or from a dataframe series:
+ ```python
+ radiogroup = mo.ui.radio.from_series(df["column_name"])
+ ```
+
+ Attributes:
+ value (Any): The value of the selected radio option.
+ options (dict): A dict mapping option name to option value.
+
+ Args:
+ options (Sequence[str] | dict[str, Any]): Sequence of text options, or dict
+ mapping option name to option value.
+ value (str, optional): Default option name, if None, starts with nothing
+ checked. Defaults to None.
+ inline (bool, optional): Whether to display options inline. Defaults to False.
+ label (str, optional): Optional markdown label for the element. Defaults to "".
+ on_change (Callable[[Any], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
"""
_name: Final[str] = "marimo-radio"
@@ -691,34 +686,32 @@ class radio(UIElement[Optional[str], Any]):
@mddoc
class text(UIElement[str, str]):
- """
- A text input.
-
- **Example.**
-
- ```python
- text = mo.ui.text(value="Hello, World!")
- ```
-
- **Attributes.**
-
- - `value`: a string of the input's contents
-
- **Initialization Args.**
-
- - `value`: default value of text box
- - `placeholder`: placeholder text to display when the text area is empty
- - `kind`: input kind, one of `"text"`, `"password"`, `"email"`, or `"url"`
- defaults to `"text"`
- - `max_length`: maximum length of input
- - `disabled`: whether the input is disabled
- - `debounce`: whether the input is debounced. If number, debounce by
- that many milliseconds. If True, then value is only emitted on Enter
- or when the input loses focus.
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
+ """A text input.
+
+ Examples:
+ ```python
+ text = mo.ui.text(value="Hello, World!")
+ ```
+
+ Attributes:
+ value (str): A string of the input's contents.
+
+ Args:
+ value (str, optional): Default value of text box. Defaults to "".
+ placeholder (str, optional): Placeholder text to display when the text area
+ is empty. Defaults to "".
+ kind (Literal["text", "password", "email", "url"], optional): Input kind.
+ Defaults to "text".
+ max_length (int, optional): Maximum length of input. Defaults to None.
+ disabled (bool, optional): Whether the input is disabled. Defaults to False.
+ debounce (bool | int, optional): Whether the input is debounced. If number,
+ debounce by that many milliseconds. If True, then value is only emitted
+ on Enter or when the input loses focus. Defaults to True.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[str], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
+ full_width (bool, optional): Whether the input should take up the full width
+ of its container. Defaults to False.
"""
_name: Final[str] = "marimo-text"
@@ -757,33 +750,31 @@ class text(UIElement[str, str]):
@mddoc
class text_area(UIElement[str, str]):
- """
- A text area that is larger than `ui.text`.
-
- **Example.**
-
- ```python
- text_area = mo.ui.text_area()
- ```
-
- **Attributes.**
-
- - `value`: a string of the text area contents
-
- **Initialization Args.**
-
- - `value`: initial value of the text area
- - `placeholder`: placeholder text to display when the text area is empty
- - `max_length`: maximum length of input
- - `disabled`: whether the input is disabled
- - `debounce`: whether the input is debounced. If number, debounce by that
- many milliseconds. If True, then value is only emitted on Ctrl+Enter
- or when the input loses focus.
- - `rows`: number of rows of text to display
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
+ """A text area that is larger than `ui.text`.
+
+ Examples:
+ ```python
+ text_area = mo.ui.text_area()
+ ```
+
+ Attributes:
+ value (str): A string of the text area contents.
+
+ Args:
+ value (str, optional): Initial value of the text area. Defaults to "".
+ placeholder (str, optional): Placeholder text to display when the text area
+ is empty. Defaults to "".
+ max_length (int, optional): Maximum length of input. Defaults to None.
+ disabled (bool, optional): Whether the input is disabled. Defaults to False.
+ debounce (bool | int, optional): Whether the input is debounced. If number,
+ debounce by that many milliseconds. If True, then value is only emitted
+ on Ctrl+Enter or when the input loses focus. Defaults to True.
+ rows (int, optional): Number of rows of text to display. Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[str], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
+ full_width (bool, optional): Whether the input should take up the full width
+ of its container. Defaults to False.
"""
_name: Final[str] = "marimo-text-area"
@@ -825,29 +816,31 @@ class code_editor(UIElement[str, str]):
"""
A code editor.
- **Example.**
-
- ```python
- code_editor = mo.ui.code_editor()
- ```
-
- **Attributes.**
-
- - `value`: a string of the code editor contents
-
- **Initialization Args.**
-
- - `value`: initial value of the code editor
- - `language`: language of the code editor, defaults to `"python"`; most
- major languages are supported, including "sql", "javascript",
- "typescript", "html", "css", "c", "cpp", "rust", and more
- - `placeholder`: placeholder text to display when the code editor is empty
- - `theme`: theme of the code editor, defaults to the editor's default
- - `disabled`: whether the input is disabled
- - `min_height`: minimum height of the code editor in pixels
- - `max_height`: maximum height of the code editor in pixels
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Examples:
+ ```python
+ code_editor = mo.ui.code_editor()
+ ```
+
+ Attributes:
+ value (str): A string of the code editor contents.
+
+ Args:
+ value (str, optional): Initial value of the code editor. Defaults to "".
+ language (str, optional): Language of the code editor. Most major languages
+ are supported, including "sql", "javascript", "typescript", "html",
+ "css", "c", "cpp", "rust", and more. Defaults to "python".
+ placeholder (str, optional): Placeholder text to display when the code editor
+ is empty. Defaults to "".
+ theme (Literal["light", "dark"], optional): Theme of the code editor.
+ Defaults to the editor's default.
+ disabled (bool, optional): Whether the input is disabled. Defaults to False.
+ min_height (int, optional): Minimum height of the code editor in pixels.
+ Defaults to None.
+ max_height (int, optional): Maximum height of the code editor in pixels.
+ Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[str], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
"""
_name: Final[str] = "marimo-code-editor"
@@ -895,49 +888,45 @@ class code_editor(UIElement[str, str]):
@mddoc
class dropdown(UIElement[List[str], Any]):
- """
- A dropdown menu.
-
- **Example.**
-
- ```python
- dropdown = mo.ui.dropdown(
- options=["a", "b", "c"], value="a", label="choose one"
- )
- ```
-
- ```python
- dropdown = mo.ui.dropdown(
- options={"one": 1, "two": 2, "three": 3},
- value="one",
- label="pick a number",
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- dropdown = mo.ui.dropdown.from_series(df["column_name"])
- ```
-
- **Attributes.**
-
- - `value`: the selected value, or `None` if no selection
- - `options`: a dict mapping option name to option value
- - `selected_key`: the selected option's key, or `None` if no selection
+ """A dropdown selector.
- **Initialization Args.**
+ Examples:
+ ```python
+ dropdown = mo.ui.dropdown(
+ options=["a", "b", "c"], value="a", label="choose one"
+ )
+ ```
- - `options`: sequence of text options, or dict mapping option name
- to option value
- - `value`: default option name
- - `allow_select_none`: whether to include special option (`"--"`) for a
- `None` value; when `None`, defaults to `True` when
- `value` is `None`
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
+ ```python
+ dropdown = mo.ui.dropdown(
+ options={"one": 1, "two": 2, "three": 3},
+ value="one",
+ label="pick a number",
+ )
+ ```
+
+ Or from a dataframe series:
+ ```python
+ dropdown = mo.ui.dropdown.from_series(df["column_name"])
+ ```
+
+ Attributes:
+ value (Any): The selected value, or None if no selection.
+ options (dict): A dict mapping option name to option value.
+ selected_key (str, optional): The selected option's key, or None if no selection.
+
+ Args:
+ options (Sequence[str] | dict[str, Any]): Sequence of text options, or dict
+ mapping option name to option value.
+ value (str, optional): Default option name. Defaults to None.
+ allow_select_none (bool, optional): Whether to include special option ("--")
+ for a None value; when None, defaults to True when value is None.
+ Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[Any], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
+ full_width (bool, optional): Whether the input should take up the full width
+ of its container. Defaults to False.
"""
_MAX_OPTIONS: Final[int] = 1000
@@ -1021,38 +1010,36 @@ class dropdown(UIElement[List[str], Any]):
@mddoc
class multiselect(UIElement[List[str], List[object]]):
- """
- A multiselect input.
+ """A multiselect input.
- **Example.**
-
- ```python
- multiselect = mo.ui.multiselect(
- options=["a", "b", "c"], label="choose some options"
- )
- ```
-
- Or from a dataframe series:
-
- ```python
- multiselect = mo.ui.multiselect.from_series(df["column_name"])
- ```
-
- **Attributes.**
-
- - `value`: the selected values, or `None` if no selection
- - `options`: a dict mapping option name to option value
-
- **Initialization Args.**
-
- - `options`: sequence of text options, or dict mapping option name
- to option value
- - `value`: a list of initially selected options
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
- - `max_selections`: maximum number of items that can be selected
+ Examples:
+ ```python
+ multiselect = mo.ui.multiselect(
+ options=["a", "b", "c"], label="choose some options"
+ )
+ ```
+
+ Or from a dataframe series:
+ ```python
+ multiselect = mo.ui.multiselect.from_series(df["column_name"])
+ ```
+
+ Attributes:
+ value (List[object]): The selected values, or None if no selection.
+ options (dict): A dict mapping option name to option value.
+
+ Args:
+ options (Sequence[str] | dict[str, Any]): Sequence of text options, or dict
+ mapping option name to option value.
+ value (Sequence[str], optional): A list of initially selected options.
+ Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[List[object]], None], optional): Optional callback to run
+ when this element's value changes. Defaults to None.
+ full_width (bool, optional): Whether the input should take up the full width
+ of its container. Defaults to False.
+ max_selections (int, optional): Maximum number of items that can be selected.
+ Defaults to None.
"""
_MAX_OPTIONS: Final[int] = 100000
@@ -1119,46 +1106,47 @@ class multiselect(UIElement[List[str], List[object]]):
@mddoc
class button(UIElement[Any, Any]):
- """
- A button with an optional callback and optional value.
-
- **Example.**
-
- ```python
- # a button that when clicked will execute
- # any cells referencing that button
- button = mo.ui.button()
- ```
-
- ```python
- # a counter implementation
- counter_button = mo.ui.button(
- value=0, on_click=lambda value: value + 1, label="increment"
- )
-
- # adding intent
- delete_button = mo.ui.button(
- label="Do not click",
- kind="danger",
- )
- ```
-
- **Attributes.**
-
- - `value`: the value of the button
-
- **Initialization Args.**
+ """A button with an optional callback and optional value.
+
+ Examples:
+ ```python
+ # a button that when clicked will execute
+ # any cells referencing that button
+ button = mo.ui.button()
+ ```
+
+ ```python
+ # a counter implementation
+ counter_button = mo.ui.button(
+ value=0, on_click=lambda value: value + 1, label="increment"
+ )
- - `on_click`: a callable called on click that takes the current
- value of the button and returns a new value
- - `value`: an initial value for the button
- - `kind`: 'neutral', 'success', 'warn', or 'danger'
- - `disabled`: whether the button is disabled
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
- - `keyboard_shortcut`: keyboard shortcut to trigger the button (e.g. 'Ctrl-L')
+ # adding intent
+ delete_button = mo.ui.button(
+ label="Do not click",
+ kind="danger",
+ )
+ ```
+
+ Attributes:
+ value (Any): The value of the button.
+
+ Args:
+ on_click (Callable[[Any], Any], optional): A callable called on click that
+ takes the current value of the button and returns a new value.
+ Defaults to None.
+ value (Any, optional): An initial value for the button. Defaults to None.
+ kind (Literal["neutral", "success", "warn", "danger"], optional): Button
+ style. Defaults to "neutral".
+ disabled (bool, optional): Whether the button is disabled. Defaults to False.
+ tooltip (str, optional): Tooltip text for the button. Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "click here".
+ on_change (Callable[[Any], None], optional): Optional callback to run when
+ this element's value changes. Defaults to None.
+ full_width (bool, optional): Whether the input should take up the full width
+ of its container. Defaults to False.
+ keyboard_shortcut (str, optional): Keyboard shortcut to trigger the button
+ (e.g. 'Ctrl-L'). Defaults to None.
"""
_name: Final[str] = "marimo-button"
@@ -1223,76 +1211,73 @@ class FileUploadResults:
@mddoc
class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
- """
- A button or drag-and-drop area to upload a file.
+ """A button or drag-and-drop area to upload a file.
- Once a file is uploaded, the UI element's value is a list of
- `namedtuples (name, contents)`, where `name` is the filename and
- `contents` is the contents of the file. Alternatively, use the methods
- `name(index: int = 0)` and `contents(index: int = 0)` to retrieve the
- name or contents of the file at a specified index.
+ Once a file is uploaded, the UI element's value is a list of namedtuples
+ (name, contents), where name is the filename and contents is the contents
+ of the file. Alternatively, use the methods name(index: int = 0) and
+ contents(index: int = 0) to retrieve the name or contents of the file at a
+ specified index.
- Use the `kind` argument to switch between a button and a drag-and-drop
- area.
+ Use the kind argument to switch between a button and a drag-and-drop area.
The maximum file size is 100MB.
- **Examples.**
-
- Uploading a single file:
-
- ```python
- f = mo.ui.file()
-
- # access the uploaded file's name
- f.value[0].name
- # or
- f.name()
-
- # access the uploaded file's contents
- f.value[0].contents
- # or
- f.contents()
- ```
-
- Uploading multiple files, accepting only .png and .jpg extensions:
-
- ```python
- f = mo.ui.file(filetypes=[".png", ".jpg"], multiple=True)
-
- # access an uploaded file's name
- f.value[index].name
- # or
- f.name(index)
-
- # access the uploaded file's contents
- f.value[index].contents
- # or
- f.contents(index)
- ```
-
- **Attributes.**
-
- - `value`: a sequence of `FileUploadResults`, which have string `name` and
- `bytes` `contents` fields
-
- **Methods.**
-
- - `name(self, index: int = 0) -> Optional[str]`: Get the name of the
- uploaded file at `index`.
- - `contents(self, index: int = 0) -> Optional[bytes]`: Get the contents of
- the uploaded file at `index`.
-
- **Initialization Args.**
-
- - `filetypes`: the file types accepted; for example,
- `filetypes=[".png", ".jpg"]`. If `None`, all files are accepted.
- In addition to extensions, you may provide `"audio/*"`, `"video/*"`,
- or `"image/*"` to accept any audio, video, or image file.
- - `multiple`: if True, allow the user to upload multiple files
- - `kind`: `"button"` or `"area"`
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Examples:
+ Uploading a single file:
+ ```python
+ f = mo.ui.file()
+
+ # access the uploaded file's name
+ f.value[0].name
+ # or
+ f.name()
+
+ # access the uploaded file's contents
+ f.value[0].contents
+ # or
+ f.contents()
+ ```
+
+ Uploading multiple files, accepting only .png and .jpg extensions:
+ ```python
+ f = mo.ui.file(filetypes=[".png", ".jpg"], multiple=True)
+
+ # access an uploaded file's name
+ f.value[index].name
+ # or
+ f.name(index)
+
+ # access the uploaded file's contents
+ f.value[index].contents
+ # or
+ f.contents(index)
+ ```
+
+ Attributes:
+ value (Sequence[FileUploadResults]): A sequence of FileUploadResults,
+ which have string name and bytes contents fields.
+
+ Methods:
+ name(index: int = 0) -> Optional[str]: Get the name of the uploaded file
+ at index.
+ contents(index: int = 0) -> Optional[bytes]: Get the contents of the
+ uploaded file at index.
+
+ Args:
+ filetypes (Sequence[str], optional): The file types accepted; for example,
+ filetypes=[".png", ".jpg"]. If None, all files are accepted.
+ In addition to extensions, you may provide "audio/*", "video/*",
+ or "image/*" to accept any audio, video, or image file.
+ Defaults to None.
+ multiple (bool, optional): If True, allow the user to upload multiple
+ files. Defaults to False.
+ kind (Literal["button", "area"], optional): Type of upload interface.
+ Defaults to "button".
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[Sequence[FileUploadResults]], None], optional):
+ Optional callback to run when this element's value changes.
+ Defaults to None.
"""
_name: Final[str] = "marimo-file"
@@ -1341,14 +1326,32 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
)
def name(self, index: int = 0) -> Optional[str]:
- """Get file name at index."""
+ """Get file name at index.
+
+ Args:
+ index (int, optional): Index of the file to get the name from.
+ Defaults to 0.
+
+ Returns:
+ Optional[str]: The name of the file at the specified index,
+ or None if index is out of range.
+ """
if not self.value or index >= len(self.value):
return None
else:
return self.value[index].name
def contents(self, index: int = 0) -> Optional[bytes]:
- """Get file contents at index."""
+ """Get file contents at index.
+
+ Args:
+ index (int, optional): Index of the file to get the contents from.
+ Defaults to 0.
+
+ Returns:
+ Optional[bytes]: The contents of the file at the specified index,
+ or None if index is out of range.
+ """
if not self.value or index >= len(self.value):
return None
else:
@@ -1367,40 +1370,41 @@ class ListDirectoryResponse:
@mddoc
class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):
- """
- File browser for browsing and selecting server-side files.
+ """File browser for browsing and selecting server-side files.
- **Examples.**
-
- Selecting multiple files:
-
- ```python
- file_browser = mo.ui.file_browser(
- initial_path="path/to/dir", multiple=True
- )
-
- # Access the selected file path(s):
- file_browser.path(index)
-
- # Get name of selected file(s)
- file_browser.name(index)
- ```
-
- **Attributes.**
-
- - `value`: a sequence of file paths representing selected files.
-
- **Initialization Args.**
+ Examples:
+ Selecting multiple files:
+ ```python
+ file_browser = mo.ui.file_browser(
+ initial_path="path/to/dir", multiple=True
+ )
- - `initial_path`: starting directory, default current working directory.
- - `filetypes`: the file types to display in each directory; for example,
- `filetypes=[".txt", ".csv"]`. If `None`, all files are displayed.
- - `selection_mode`: either "file" or "directory".
- - `multiple`: if True, allow the user to select multiple files.
- - `restrict_navigation`: if True, prevent the user from navigating
- any level above the given path.
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ # Access the selected file path(s):
+ file_browser.path(index)
+
+ # Get name of selected file(s)
+ file_browser.name(index)
+ ```
+
+ Attributes:
+ value (Sequence[FileInfo]): A sequence of file paths representing selected
+ files.
+
+ Args:
+ initial_path (str, optional): Starting directory. Defaults to current
+ working directory.
+ filetypes (Sequence[str], optional): The file types to display in each
+ directory; for example, filetypes=[".txt", ".csv"]. If None, all
+ files are displayed. Defaults to None.
+ selection_mode (str, optional): Either "file" or "directory". Defaults to
+ "file".
+ multiple (bool, optional): If True, allow the user to select multiple
+ files. Defaults to True.
+ restrict_navigation (bool, optional): If True, prevent the user from
+ navigating any level above the given path. Defaults to False.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[Sequence[FileInfo]], None], optional): Optional
+ callback to run when this element's value changes. Defaults to None.
"""
_name: Final[str] = "marimo-file-browser"
@@ -1509,14 +1513,32 @@ class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):
)
def name(self, index: int = 0) -> Optional[str]:
- """Get file name at index."""
+ """Get file name at index.
+
+ Args:
+ index (int, optional): Index of the file to get the name from.
+ Defaults to 0.
+
+ Returns:
+ Optional[str]: The name of the file at the specified index,
+ or None if index is out of range.
+ """
if not self.value or index >= len(self.value):
return None
else:
return self.value[index].name
def path(self, index: int = 0) -> Optional[str]:
- """Get file path at index."""
+ """Get file path at index.
+
+ Args:
+ index (int, optional): Index of the file to get the path from.
+ Defaults to 0.
+
+ Returns:
+ Optional[str]: The path of the file at the specified index,
+ or None if index is out of range.
+ """
if not self.value or index >= len(self.value):
return None
else:
@@ -1533,68 +1555,77 @@ class ValueArgs:
@mddoc
class form(UIElement[Optional[JSONTypeBound], Optional[T]]):
- """
- A submittable form linked to a UIElement.
+ """A submittable form linked to a UIElement.
Use a `form` to prevent sending UI element values to Python until a button
is clicked.
- The value of a `form` is the value of the underlying
- element the last time the form was submitted.
-
- **Example.**
-
- ```python
- # Create a form with chaining
- form = mo.ui.slider(1, 100).form()
- ```
-
- ```python
- # Create a form with multiple elements
- form = (
- mo.md('''
- **Your form.**
-
- {name}
-
- {date}
- ''')
- .batch(
- name=mo.ui.text(label="name"),
- date=mo.ui.date(label="date"),
+ The value of a `form` is the value of the underlying element the last time
+ the form was submitted.
+
+ Examples:
+ Create a form with chaining:
+ ```python
+ # Create a form with chaining
+ form = mo.ui.slider(1, 100).form()
+ ```
+
+ Create a form with multiple elements:
+ ```python
+ # Create a form with multiple elements
+ form = (
+ mo.md('''
+ **Your form.**
+
+ {name}
+
+ {date}
+ ''')
+ .batch(
+ name=mo.ui.text(label="name"),
+ date=mo.ui.date(label="date"),
+ )
+ .form(show_clear_button=True, bordered=False)
)
- .form(show_clear_button=True, bordered=False)
- )
- ```
-
- ```python
- # Instantiate a form directly
- form = mo.ui.form(element=mo.ui.slider(1, 100))
- ```
-
- **Attributes.**
-
- - `value`: the value of the wrapped element when the form's submit button
- was last clicked
- - `element`: a copy of the wrapped element
-
- **Initialization Args.**
-
- - `element`: the element to wrap
- - `bordered`: whether the form should have a border
- - `loading`: whether the form should be in a loading state
- - `submit_button_label`: the label of the submit button
- - `submit_button_tooltip`: the tooltip of the submit button
- - `submit_button_disabled`: whether the submit button should be disabled
- - `clear_on_submit`: whether the form should clear its contents after
- submitting
- - `show_clear_button`: whether the form should show a clear button
- - `clear_button_label`: the label of the clear button
- - `clear_button_tooltip`: the tooltip of the clear button
- - `validate`: a function that takes the form's value and returns an error
- message if the value is invalid, or `None` if the value is valid
- - `label`: markdown label for the form
- - `on_change`: optional callback to run when this element's value changes
+ ```
+
+ Instantiate a form directly:
+ ```python
+ # Instantiate a form directly
+ form = mo.ui.form(element=mo.ui.slider(1, 100))
+ ```
+
+ Attributes:
+ value (Any): The value of the wrapped element when the form's submit
+ button was last clicked.
+ element (UIElement): A copy of the wrapped element.
+
+ Args:
+ element (UIElement[JSONTypeBound, T]): The element to wrap.
+ bordered (bool, optional): Whether the form should have a border.
+ Defaults to True.
+ loading (bool, optional): Whether the form should be in a loading state.
+ Defaults to False.
+ submit_button_label (str, optional): The label of the submit button.
+ Defaults to "Submit".
+ submit_button_tooltip (str, optional): The tooltip of the submit button.
+ Defaults to None.
+ submit_button_disabled (bool, optional): Whether the submit button should
+ be disabled. Defaults to False.
+ clear_on_submit (bool, optional): Whether the form should clear its
+ contents after submitting. Defaults to False.
+ show_clear_button (bool, optional): Whether the form should show a clear
+ button. Defaults to False.
+ clear_button_label (str, optional): The label of the clear button.
+ Defaults to "Clear".
+ clear_button_tooltip (str, optional): The tooltip of the clear button.
+ Defaults to None.
+ validate (Callable[[Optional[JSONType]], Optional[str]], optional): A
+ function that takes the form's value and returns an error message if
+ the value is invalid, or None if the value is valid. Defaults to None.
+ label (str, optional): Markdown label for the form. Defaults to "".
+ on_change (Callable[[Optional[T]], None], optional): Optional callback to
+ run when this element's value changes. Defaults to None.
"""
_name: Final[str] = "marimo-form"
diff --git a/marimo/_plugins/ui/_impl/microphone.py b/marimo/_plugins/ui/_impl/microphone.py
index b997d47790..04fc85d7a7 100644
--- a/marimo/_plugins/ui/_impl/microphone.py
+++ b/marimo/_plugins/ui/_impl/microphone.py
@@ -16,25 +16,23 @@ class microphone(UIElement[str, io.BytesIO]):
Use `mo.ui.microphone` to record audio via the user's browser. The
user must grant permission to use the microphone.
- **Example.**
-
- ```python
- mic = mo.ui.microphone()
- mic
- ```
-
- ```python
- mo.audio(mic.value)
- ```
-
- **Attributes.**
-
- - `value`: The blob of the recorded audio, as an `io.BytesIO` object.
-
- **Initialization Args.**
-
- - `label`: optional markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Examples:
+ ```python
+ mic = mo.ui.microphone()
+ mic
+ ```
+
+ ```python
+ mo.audio(mic.value)
+ ```
+
+ Attributes:
+ value (io.BytesIO): The blob of the recorded audio, as an `io.BytesIO` object.
+
+ Args:
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Optional[Callable[[io.BytesIO], None]], optional): Optional callback
+ to run when this element's value changes.
"""
name: Final[str] = "marimo-microphone"
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 7185433a26..7c9af46009 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -49,53 +49,54 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):
This function currently only supports scatter plots, treemaps charts,
and sunbursts charts.
- **Example.**
-
- ```python
- import plotly.express as px
- import marimo as mo
- from vega_datasets import data
-
- _plot = px.scatter(
- data.cars(), x="Horsepower", y="Miles_per_Gallon", color="Origin"
- )
-
- plot = mo.ui.plotly(_plot)
- ```
-
- ```
- # View the plot and selected data
- mo.hstack([plot, plot.value])
- ```
-
- Or with custom configuration:
-
- ```python
- plot = mo.ui.plotly(
- _plot,
- config={"staticPlot": True},
- )
- ```
-
- **Attributes.**
-
- - `value`: a dict of the plot data
- - `ranges`: the selection of the plot; this may be an interval along
- the name of an axis
-
- **Initialization Args.**
-
- - `figure`: A `plotly.graph_objects.Figure`
- - `config`: optional configuration for the plot.
- This is a dictionary that is passed directly to the plotly.
- See the plotly documentation for more information:
- https://plotly.com/javascript/configuration-options/
- This takes precedence over the default configuration of the renderer.
- - `renderer_name`: optional renderer to use for the plot.
- If this is not provided, the default renderer (pio.renderers.default)
- is used.
- - `label`: optional markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Examples:
+ ```python
+ import plotly.express as px
+ import marimo as mo
+ from vega_datasets import data
+
+ _plot = px.scatter(
+ data.cars(), x="Horsepower", y="Miles_per_Gallon", color="Origin"
+ )
+
+ plot = mo.ui.plotly(_plot)
+ ```
+
+ ```python
+ # View the plot and selected data
+ mo.hstack([plot, plot.value])
+ ```
+
+ Or with custom configuration:
+
+ ```python
+ plot = mo.ui.plotly(
+ _plot,
+ config={"staticPlot": True},
+ )
+ ```
+
+ Attributes:
+ value (Dict[str, Any]): A dict of the plot data.
+ ranges (Dict[str, List[float]]): The selection of the plot; this may be an
+ interval along the name of an axis.
+ points (List[Dict[str, Any]]): The selected points data.
+ indices (List[int]): The indices of selected points.
+
+ Args:
+ figure (plotly.graph_objects.Figure): A plotly Figure object.
+ config (Optional[Dict[str, Any]], optional): Configuration for the plot.
+ This is a dictionary that is passed directly to plotly.
+ See the plotly documentation for more information:
+ https://plotly.com/javascript/configuration-options/
+ This takes precedence over the default configuration of the renderer.
+ Defaults to None.
+ renderer_name (Optional[str], optional): Renderer to use for the plot.
+ If this is not provided, the default renderer (`pio.renderers.default`)
+ is used. Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Optional[Callable[[JSONType], None]], optional): Callback to run
+ when this element's value changes. Defaults to None.
"""
name: Final[str] = "marimo-plotly"
@@ -149,6 +150,13 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):
@property
def ranges(self) -> Dict[str, List[float]]:
+ """Get the range selection of the plot.
+
+ Returns:
+ Dict[str, List[float]]: A dictionary mapping field names to their
+ selected ranges, where each range is a list of [min, max] values.
+ Returns an empty dict if no range selection exists.
+ """
if not self._selection_data:
return {}
if "range" not in self._selection_data:
@@ -157,6 +165,12 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):
@property
def points(self) -> List[Dict[str, Any]]:
+ """Get the selected points data from the plot.
+
+ Returns:
+ List[Dict[str, Any]]: A list of dictionaries containing the data for
+ each selected point. Returns an empty list if no points are selected.
+ """
if not self._selection_data:
return []
if "points" not in self._selection_data:
@@ -165,6 +179,12 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):
@property
def indices(self) -> List[int]:
+ """Get the indices of selected points in the plot.
+
+ Returns:
+ List[int]: A list of indices corresponding to the selected points.
+ Returns an empty list if no points are selected.
+ """
if not self._selection_data:
return []
if "indices" not in self._selection_data:
diff --git a/marimo/_plugins/ui/_impl/refresh.py b/marimo/_plugins/ui/_impl/refresh.py
index 289672fb08..2c3f09cb9a 100644
--- a/marimo/_plugins/ui/_impl/refresh.py
+++ b/marimo/_plugins/ui/_impl/refresh.py
@@ -9,46 +9,43 @@ from marimo._plugins.ui._core.ui_element import UIElement
@mddoc
class refresh(UIElement[int, int]):
- """
- A refresh button that will auto-refresh its descendants for a
- given interval.
+ """A refresh button that will auto-refresh its descendants for a given interval.
Each option value can either be a number (int or float) in seconds or a
- human-readable string (e.g. "1s", "10s", "1m").
-
- You can also combine multiple time units (e.g. "1m 30s").
-
- Note: The refresh interval may not be exact, as it depends on the
- time it takes to render the content and the time it takes to send
- the content to the client. Also, due to the buffering of UI element
- changes, if the downstream cells take a long time to render, the
- refresh interval may be longer than expected.
-
- **Example.**
-
- ```python
- refresh_button = mo.ui.refresh(
- options=["1m", "5m 30s", "10m"],
- default_interval="10m",
- )
- refresh_button
- ```
-
- **Attributes.**
-
- - `value`: The time in seconds since the refresh has been activated.
-
- **Initialization Args.**
-
- - `options`: The options for the refresh interval, as a list of
- human-readable strings or numbers (int or float) in seconds.
- If no options are provided and default_interval is provided,
- the options will be generated automatically.
- If no options are provided and default_interval is not provided,
- the refresh button will not be displayed with a dropdown for auto-refresh.
- - `default_interval`: The default value of the refresh interval.
- - `label`: optional markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ human-readable string (e.g. "1s", "10s", "1m"). You can also combine multiple
+ time units (e.g. "1m 30s").
+
+ Note:
+ The refresh interval may not be exact, as it depends on the
+ time it takes to render the content and the time it takes to send
+ the content to the client. Also, due to the buffering of UI element
+ changes, if the downstream cells take a long time to render, the
+ refresh interval may be longer than expected.
+
+ Examples:
+ ```python
+ refresh_button = mo.ui.refresh(
+ options=["1m", "5m 30s", "10m"],
+ default_interval="10m",
+ )
+ refresh_button
+ ```
+
+ Attributes:
+ value (int): The time in seconds since the refresh has been activated.
+
+ Args:
+ options (Optional[list[Union[int, float, str]]], optional): The options for the
+ refresh interval, as a list of human-readable strings or numbers (int or float)
+ in seconds. If no options are provided and default_interval is provided,
+ the options will be generated automatically. If no options are provided and
+ default_interval is not provided, the refresh button will not be displayed
+ with a dropdown for auto-refresh.
+ default_interval (Optional[Union[int, float, str]], optional): The default value
+ of the refresh interval.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Optional[Callable[[int], None]], optional): Optional callback to run
+ when this element's value changes.
"""
name: Final[str] = "marimo-refresh"
diff --git a/marimo/_plugins/ui/_impl/run_button.py b/marimo/_plugins/ui/_impl/run_button.py
index 839078470a..a65fe3959e 100644
--- a/marimo/_plugins/ui/_impl/run_button.py
+++ b/marimo/_plugins/ui/_impl/run_button.py
@@ -11,51 +11,48 @@ from marimo._runtime.context.types import ContextNotInitializedError
@mddoc
class run_button(UIElement[Any, Any]):
- """
- A button that can be used to trigger computation.
-
- **Example.**
-
- ```python
- # a button that when clicked will have its value set to True;
- # any cells referencing that button will automatically run.
- button = mo.ui.run_button()
- button
- ```
-
- ```python
- slider = mo.ui.slider(1, 10)
- slider
- ```
-
- ```python
- # if the button hasn't been clicked, don't run.
- mo.stop(not button.value)
-
- slider.value
- ```
-
- When clicked, `run_button`'s value is set to `True`, and any cells
- referencing it are run. After those cells are run, `run_button`'s
- value will automatically be set back to `False` as long as automatic
- execution is enabled.
-
- **Attributes.**
-
- - `value`: the value of the button; `True` when clicked, and reset to
- `False` after cells referencing the button finish running (when
- automatic execution is enabled).
-
- **Initialization Args.**
-
- - `kind`: 'neutral', 'success', 'warn', or 'danger'
- - `disabled`: whether the button is disabled
- - `tooltip`: a tooltip to display for the button
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `full_width`: whether the input should take up the full width of its
- container
- - `keyboard_shortcut`: keyboard shortcut to trigger the button (e.g. 'Ctrl-L')
+ """A button that can be used to trigger computation.
+
+ When clicked, run_button's value is set to True, and any cells referencing it are run.
+ After those cells are run, run_button's value will automatically be set back to False
+ as long as automatic execution is enabled.
+
+ Examples:
+ ```python
+ # a button that when clicked will have its value set to True;
+ # any cells referencing that button will automatically run.
+ button = mo.ui.run_button()
+ button
+ ```
+
+ ```python
+ slider = mo.ui.slider(1, 10)
+ slider
+ ```
+
+ ```python
+ # if the button hasn't been clicked, don't run.
+ mo.stop(not button.value)
+
+ slider.value
+ ```
+
+ Attributes:
+ value (bool): The value of the button; True when clicked, and reset to False after
+ cells referencing the button finish running (when automatic execution is enabled).
+
+ Args:
+ kind (Literal["neutral", "success", "warn", "danger"], optional): Button style.
+ Defaults to "neutral".
+ disabled (bool, optional): Whether the button is disabled. Defaults to False.
+ tooltip (str, optional): A tooltip to display for the button. Defaults to None.
+ label (str, optional): Markdown label for the element. Defaults to "click to run".
+ on_change (Callable[[Any], None], optional): Optional callback to run when this
+ element's value changes.
+ full_width (bool, optional): Whether the input should take up the full width of its
+ container. Defaults to False.
+ keyboard_shortcut (str, optional): Keyboard shortcut to trigger the button
+ (e.g. 'Ctrl-L'). Defaults to None.
"""
# We reuse the button plugin on the frontend, UI/logic are the same
diff --git a/marimo/_plugins/ui/_impl/switch.py b/marimo/_plugins/ui/_impl/switch.py
index deec3d73dd..461766c75f 100644
--- a/marimo/_plugins/ui/_impl/switch.py
+++ b/marimo/_plugins/ui/_impl/switch.py
@@ -9,24 +9,21 @@ from marimo._plugins.ui._core.ui_element import UIElement
@mddoc
class switch(UIElement[bool, bool]):
- """
- A boolean switch.
-
- **Example.**
-
- ```python
- switch = mo.ui.switch()
- ```
-
- **Attributes.**
+ """A boolean switch.
- - `value`: A boolean, `True` if checked.
+ Examples:
+ ```python
+ switch = mo.ui.switch()
+ ```
- **Initialization Args.**
+ Attributes:
+ value (bool): A boolean, `True` if checked.
- - `value`: default value, True or False
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
+ Args:
+ value (bool, optional): Default value, True or False. Defaults to False.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Optional[Callable[[bool], None]], optional): Optional callback to run
+ when this element's value changes.
"""
_name: Final[str] = "marimo-switch"
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index f9d8019866..059aca4fd1 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -97,11 +97,9 @@ class SortArgs:
@mddoc
class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
- """
- A table component with selectable rows. Get the selected rows with
- `table.value`.
+ """A table component with selectable rows.
- The table data can be supplied a:
+ Get the selected rows with `table.value`. The table data can be supplied as:
1. a list of dicts, with one dict for each row, keyed by column names;
2. a list of values, representing a table with a single column;
@@ -110,104 +108,101 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
5. an Ibis dataframe; or
6. a PyArrow table.
- **Examples.**
+ Examples:
+ Create a table from a list of dicts, one for each row:
- Create a table from a list of dicts, one for each row.
+ ```python
+ table = mo.ui.table(
+ data=[
+ {"first_name": "Michael", "last_name": "Scott"},
+ {"first_name": "Dwight", "last_name": "Schrute"},
+ ],
+ label="Users",
+ )
+ ```
- ```python
- table = mo.ui.table(
- data=[
- {"first_name": "Michael", "last_name": "Scott"},
- {"first_name": "Dwight", "last_name": "Schrute"},
- ],
- label="Users",
- )
- ```
-
- Create a table from a single column of data:
-
- table = mo.ui.table(
- data=[
- {'first_name': 'Michael', 'last_name': 'Scott'},
- {'first_name': 'Dwight', 'last_name': 'Schrute'}
- ],
- label='Users'
- )
-
- Create a table from a dataframe:
-
- ```python
- # df is a Pandas or Polars dataframe
- table = mo.ui.table(
- data=df,
- # use pagination when your table has many rows
- pagination=True,
- label="Dataframe",
- )
- ```
-
- Create a table with format mapping:
-
- ```python
- # format_mapping is a dict keyed by column names,
- # with values as formatting functions or strings
- def format_name(name):
- return name.upper()
-
-
- table = mo.ui.table(
- data=[
- {"first_name": "Michael", "last_name": "Scott", "age": 45},
- {"first_name": "Dwight", "last_name": "Schrute", "age": 40},
- ],
- format_mapping={
- "first_name": format_name, # Use callable to format first names
- "age": "{:.1f}".format, # Use string format for age
- },
- label="Format Mapping",
- )
- ```
- In each case, access the table data with `table.value`.
-
- **Attributes.**
-
- - `value`: the selected rows, in the same format as the original data,
- or `None` if no selection
- - `data`: the original table data
-
- **Initialization Args.**
-
- - `data`: Values can be primitives (`str`,
- `int`, `float`, `bool`, or `None`) or marimo elements: e.g.
- `mo.ui.button(...)`, `mo.md(...)`, `mo.as_html(...)`, etc. Data can be
- passed in many ways:
- - as dataframes: a pandas dataframe, a polars dataframe
- - as rows: a list of dicts, where each dict represents a row in the
- table
- - as columns: a dict keyed by column names, where the value of each
- entry is a list representing a column
- - as a single column: a list of values
- - `pagination`: whether to paginate; if `False`, all rows will be shown
- defaults to `True` when above 10 rows, `False` otherwise
- - `selection`: 'single' or 'multi' to enable row selection, or `None` to
- disable
- - `page_size`: the number of rows to show per page.
- defaults to 10
- - `show_column_summaries`: whether to show column summaries
- defaults to `True` when the table has less than 40 columns, `False` otherwise
- - `show_download`: whether to show the download button
- defaults to `True` for dataframes, `False` otherwise
- - `format_mapping`: a mapping from column names to formatting strings
- or functions
- - `freeze_columns_left`: list of column names to freeze on the left
- - `freeze_columns_right`: list of column names to freeze on the right
- - `text_justify_columns`: dictionary of column names to text justification
- options: `left`, `center`, `right`
- - `wrapped_columns`: list of column names to wrap
- - `label`: markdown label for the element
- - `on_change`: optional callback to run when this element's value changes
- - `max_columns`: maximum number of columns to display, defaults to 50.
- Set to None to show all columns.
+ Create a table from a single column of data:
+
+ ```python
+ table = mo.ui.table(
+ data=[
+ {"first_name": "Michael", "last_name": "Scott"},
+ {"first_name": "Dwight", "last_name": "Schrute"},
+ ],
+ label="Users",
+ )
+ ```
+
+ Create a table from a dataframe:
+
+ ```python
+ # df is a Pandas or Polars dataframe
+ table = mo.ui.table(
+ data=df,
+ # use pagination when your table has many rows
+ pagination=True,
+ label="Dataframe",
+ )
+ ```
+
+ Create a table with format mapping:
+
+ ```python
+ # format_mapping is a dict keyed by column names,
+ # with values as formatting functions or strings
+ def format_name(name):
+ return name.upper()
+
+
+ table = mo.ui.table(
+ data=[
+ {"first_name": "Michael", "last_name": "Scott", "age": 45},
+ {"first_name": "Dwight", "last_name": "Schrute", "age": 40},
+ ],
+ format_mapping={
+ "first_name": format_name, # Use callable to format first names
+ "age": "{:.1f}".format, # Use string format for age
+ },
+ label="Format Mapping",
+ )
+ ```
+
+ In each case, access the table data with `table.value`.
+
+ Attributes:
+ value (Union[List[JSONType], IntoDataFrame]): The selected rows, in the same format
+ as the original data, or None if no selection.
+ data (Union[List[JSONType], IntoDataFrame]): The original table data.
+
+ Args:
+ data (Union[List[Union[str, int, float, bool, MIME, None]], List[Dict[str, JSONType]], Dict[str, List[JSONType]], IntoDataFrame]):
+ Values can be primitives (`str`, `int`, `float`, `bool`, or `None`) or marimo elements:
+ e.g. `mo.ui.button(...)`, `mo.md(...)`, `mo.as_html(...)`, etc. Data can be passed in many ways:
+ - as dataframes: a pandas dataframe, a polars dataframe
+ - as rows: a list of dicts, where each dict represents a row in the table
+ - as columns: a dict keyed by column names, where the value of each entry is a list representing a column
+ - as a single column: a list of values
+ pagination (bool, optional): Whether to paginate; if False, all rows will be shown.
+ Defaults to True when above 10 rows, False otherwise.
+ selection (Literal["single", "multi"], optional): 'single' or 'multi' to enable row selection,
+ or None to disable. Defaults to "multi".
+ page_size (int, optional): The number of rows to show per page. Defaults to 10.
+ show_column_summaries (bool, optional): Whether to show column summaries.
+ Defaults to True when the table has less than 40 columns, False otherwise.
+ show_download (bool, optional): Whether to show the download button.
+ Defaults to True for dataframes, False otherwise.
+ format_mapping (Dict[str, Union[str, Callable[..., Any]]], optional): A mapping from
+ column names to formatting strings or functions.
+ freeze_columns_left (Sequence[str], optional): List of column names to freeze on the left.
+ freeze_columns_right (Sequence[str], optional): List of column names to freeze on the right.
+ text_justify_columns (Dict[str, Literal["left", "center", "right"]], optional):
+ Dictionary of column names to text justification options: left, center, right.
+ wrapped_columns (List[str], optional): List of column names to wrap.
+ label (str, optional): Markdown label for the element. Defaults to "".
+ on_change (Callable[[Union[List[JSONType], Dict[str, List[JSONType]], IntoDataFrame]], None], optional):
+ Optional callback to run when this element's value changes.
+ max_columns (int, optional): Maximum number of columns to display. Defaults to 50.
+ Set to None to show all columns.
"""
_name: Final[str] = "marimo-table"
@@ -426,6 +421,12 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
def data(
self,
) -> TableData:
+ """Get the original table data.
+
+ Returns:
+ TableData: The original data passed to the table constructor, in its
+ original format (list, dict, dataframe, etc.).
+ """
return self._data
def _get_banner_text(self) -> str:
@@ -445,12 +446,24 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
return unwrap_narwhals_dataframe(self._selected_manager.data) # type: ignore[no-any-return]
def download_as(self, args: DownloadAsArgs) -> str:
- # download selected rows if there are any, otherwise use all rows
- # not apply formatting here, raw data is downloaded
+ """Download the table data in the specified format.
+
+ Downloads selected rows if there are any, otherwise downloads all rows.
+ Raw data is downloaded without any formatting applied.
+
+ Args:
+ args (DownloadAsArgs): Arguments specifying the download format.
+ format must be one of 'csv' or 'json'.
+
+ Returns:
+ str: URL to download the data file.
+
+ Raises:
+ ValueError: If format is not 'csv' or 'json'.
+ """
manager = (
self._selected_manager
if self._selected_manager and self._has_any_selection
- # use _searched_manager here to download the full data
else self._searched_manager
)
@@ -463,6 +476,20 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
raise ValueError("format must be one of 'csv' or 'json'.")
def get_column_summaries(self, args: EmptyArgs) -> ColumnSummaries:
+ """Get statistical summaries for each column in the table.
+
+ Calculates summaries like null counts, min/max values, unique counts, etc.
+ for each column. Summaries are only calculated if the total number of rows
+ is below the column summary row limit.
+
+ Args:
+ args (EmptyArgs): Empty arguments object (unused).
+
+ Returns:
+ ColumnSummaries: Object containing column summaries and chart data.
+ If summaries are disabled or row limit is exceeded, returns empty
+ summaries with is_disabled flag set appropriately.
+ """
del args
if not self._show_column_summaries:
return ColumnSummaries(
@@ -553,6 +580,25 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
return result
def search(self, args: SearchTableArgs) -> SearchTableResponse:
+ """Search and filter the table data.
+
+ Applies filters, search query, and sorting to the table data. Returns
+ paginated results based on the specified page size and number.
+
+ Args:
+ args (SearchTableArgs): Search arguments containing:
+ - page_size: Number of rows per page
+ - page_number: Zero-based page index
+ - query: Optional search query string
+ - sort: Optional sorting configuration
+ - filters: Optional list of filter conditions
+ - limit: Optional row limit
+
+ Returns:
+ SearchTableResponse: Response containing:
+ - data: Filtered and formatted table data for the requested page
+ - total_rows: Total number of rows after applying filters
+ """
offset = args.page_number * args.page_size
def clamp_rows_and_columns(manager: TableManager[Any]) -> JSONType:
@@ -591,9 +637,14 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
)
def _repr_markdown_(self) -> str:
- """
- Return a markdown representation of the table.
- Useful for rendering in the GitHub viewer.
+ """Return a markdown representation of the table.
+
+ Generates a markdown or HTML representation of the table data,
+ useful for rendering in the GitHub viewer.
+
+ Returns:
+ str: HTML representation of the table if available,
+ otherwise string representation.
"""
df = self.data
if hasattr(df, "_repr_html_"):
diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.py
index 0eff6f7208..3cea08da9f 100644
--- a/marimo/_plugins/ui/_impl/tabs.py
+++ b/marimo/_plugins/ui/_impl/tabs.py
@@ -14,53 +14,47 @@ from marimo._plugins.ui._core.ui_element import UIElement
class tabs(UIElement[str, str]):
"""Display objects in a tabbed view.
- **Examples.**
-
- Show content in tabs:
-
- ```python
- tab1 = mo.vstack([
- "slider": mo.ui.slider(1, 10),
- "text": mo.ui.text(),
- "date": mo.ui.date()
- ])
-
- tab2 = mo.md("You can show arbitrary content in a tab.")
-
- tabs = mo.ui.tabs({
- "Heading 1": tab1,
- "Heading 2": tab2
- })
- ```
-
- Control which tab is selected:
-
- ```python
- tabs = mo.ui.tabs(
- {"Heading 1": tab1, "Heading 2": tab2}, value="Heading 2"
- )
- ```
-
- Tab content can be lazily loaded:
-
- ```python
- tabs = mo.ui.tabs(
- {"Heading 1": tab1, "Heading 2": expensive_component}, lazy=True
- )
- ```
-
- **Attributes.**
-
- - `value`: A string, the name of the selected tab.
-
- **Initialization Args.**
+ Examples:
+ Show content in tabs:
+ ```python
+ tab1 = mo.vstack([
+ "slider": mo.ui.slider(1, 10),
+ "text": mo.ui.text(),
+ "date": mo.ui.date()
+ ])
+
+ tab2 = mo.md("You can show arbitrary content in a tab.")
+
+ tabs = mo.ui.tabs({
+ "Heading 1": tab1,
+ "Heading 2": tab2
+ })
+ ```
+
+ Control which tab is selected:
+ ```python
+ tabs = mo.ui.tabs(
+ {"Heading 1": tab1, "Heading 2": tab2}, value="Heading 2"
+ )
+ ```
- - `tabs`: a dictionary of tab names to tab content; strings are interpreted
- as markdown
- - `value`: the name of the tab to open; defaults to the first tab
- - `lazy`: a boolean, whether to lazily load the tab content.
- This is a convenience that wraps each tab in a `mo.lazy`
- component.
+ Tab content can be lazily loaded:
+ ```python
+ tabs = mo.ui.tabs(
+ {"Heading 1": tab1, "Heading 2": expensive_component}, lazy=True
+ )
+ ```
+
+ Attributes:
+ value (str): The name of the selected tab.
+
+ Args:
+ tabs (dict[str, object]): A dictionary of tab names to tab content; strings
+ are interpreted as markdown.
+ value (str, optional): The name of the tab to open. Defaults to the first tab.
+ lazy (bool, optional): Whether to lazily load the tab content.
+ This is a convenience that wraps each tab in a `mo.lazy`
+ component. Defaults to False.
"""
_name: Final[str] = "marimo-tabs"