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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
docs: update docstrings to Google Style format (#3221)
devin-ai-integration[bot]e91cf83064b7
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex c6763037c2..c9206c88bd 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -345,47 +345,45 @@ class App:The `embed` method lets you embed the output of a notebookinto another notebook and access the values of its variables.- **Example.**-- ```python- from my_notebook import app- ```-- ```python- # execute the notebook; app.embed() can't be called in the cell- # that imported it!- result = await app.embed()- ```-- ```python- # view the notebook's visual output- result.output- ```-- ```python- # access the notebook's defined variables- result.defs- ```-- Running `await app.embed()` executes the notebook and results an object- encapsulating the notebook visual output and its definitions.-- Embedded notebook outputs are interactive: when you interact with- UI elements in an embedded notebook's output, any cell referring- to the `app` object other than the one that imported it is marked for- execution, and its internal state is automatically updated. This lets- you use notebooks as building blocks or components to create- higher-level notebooks.-- Multiple levels of nesting are supported: it's possible to embed a- notebook that in turn embeds another notebook, and marimo will do the- right thing.-- **Returns.**-- - An object `result` with two attributes: `result.output` (visual- output of the notebook) and `result.defs` (a dictionary mapping- variable names defined by the notebook to their values).+ Returns:+ An object `result` with two attributes: `result.output` (visual+ output of the notebook) and `result.defs` (a dictionary mapping+ variable names defined by the notebook to their values).++ Example:+ ```python+ from my_notebook import app+ ```++ ```python+ # execute the notebook; app.embed() can't be called in the cell+ # that imported it!+ result = await app.embed()+ ```++ ```python+ # view the notebook's visual output+ result.output+ ```++ ```python+ # access the notebook's defined variables+ result.defs+ ```++ Running `await app.embed()` executes the notebook and results an object+ encapsulating the notebook visual output and its definitions.++ Embedded notebook outputs are interactive: when you interact with+ UI elements in an embedded notebook's output, any cell referring+ to the `app` object other than the one that imported it is marked for+ execution, and its internal state is automatically updated. This lets+ you use notebooks as building blocks or components to create+ higher-level notebooks.++ Multiple levels of nesting are supported: it's possible to embed a+ notebook that in turn embeds another notebook, and marimo will do the+ right thing."""from marimo._plugins.stateless.flex import vstackfrom marimo._runtime.context.utils import running_in_notebookdiff --git a/marimo/_output/doc.py b/marimo/_output/doc.pyindex 2147a33633..74f0b76fd5 100644--- a/marimo/_output/doc.py+++ b/marimo/_output/doc.py@@ -15,14 +15,12 @@ def doc(obj: Any) -> Optional[Html]:If the object implements the `RichHelp` protocol, the documentation will berendered as markdown.- **Args.**+ Args:+ obj: The object to get documentation about.- - `obj`: The object to get documentation about.-- **Returns.**-- - Documentation as an `Html` object if the object implements `RichHelp`;- otherwise, documentation is printed to console (and nothing is returned)+ Returns:+ Documentation as an `Html` object if the object implements `RichHelp`;+ otherwise, documentation is printed to console (and nothing is returned)"""if hasattr(obj, "_rich_help_"):msg = obj._rich_help_()diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 0c2f919ab1..675de14323 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -234,33 +234,30 @@ def try_format(obj: Any, include_opinionated: bool = True) -> FormattedOutput:@mddocdef as_html(value: object) -> Html:- """Convert a value to HTML that can be embedded into markdown+ """Convert a value to HTML that can be embedded into markdown.This function returns an `Html` object representing `value`. Use it toembed values into Markdown or other HTML strings.- **Example.**-- ```python3- import matplotlib.pyplot as plt- plt.plot([1, 2])- axis = plt.gca()- mo.md(- f\"\"\"- Here is a plot:-- {mo.as_html(axis)}- \"\"\"- )- ```-- **Args.**+ Args:+ value: An object- - `value`: An object+ Returns:+ An `Html` object- **Returns.**+ Example:+ ```python3+ import matplotlib.pyplot as plt+ plt.plot([1, 2])+ axis = plt.gca()+ mo.md(+ f\"\"\"+ Here is a plot:- - An `Html` object+ {mo.as_html(axis)}+ \"\"\"+ )+ ```"""if isinstance(value, Html):return valuediff --git a/marimo/_plugins/stateless/accordion.py b/marimo/_plugins/stateless/accordion.pyindex 1daa159180..10a528f8bb 100644--- a/marimo/_plugins/stateless/accordion.py+++ b/marimo/_plugins/stateless/accordion.py@@ -13,38 +13,34 @@ from marimo._plugins.stateless.lazy import lazy as lazy_uidef accordion(items: dict[str, object], multiple: bool = False, lazy: bool = False) -> Html:- """- Accordion of one or more items.-- **Example.**-- ```python3- mo.accordion(- {"Tip": "Use accordions to let users reveal and hide content."}- )- ```-- Accordion content can be lazily loaded:-- ```python3- mo.accordion({"View total": expensive_item}, lazy=True)- ```-- where `expensive_item` is the item to render, or a callable that- returns the item to render.-- **Args.**+ """Accordion of one or more items.++ Args:+ items: a dictionary of item names to item content; strings are+ interpreted as markdown+ multiple: whether to allow multiple items to be open simultaneously+ lazy: a boolean, whether to lazily load the accordion content.+ This is a convenience that wraps each accordion in a `mo.lazy`+ component.++ Returns:+ An `Html` object.++ Example:+ ```python3+ mo.accordion(+ {"Tip": "Use accordions to let users reveal and hide content."}+ )+ ```- - `items`: a dictionary of item names to item content; strings are- interpreted as markdown- - `multiple`: whether to allow multiple items to be open simultaneously- - `lazy`: a boolean, whether to lazily load the accordion content.- This is a convenience that wraps each accordion in a `mo.lazy`- component.+ Accordion content can be lazily loaded:- **Returns.**+ ```python3+ mo.accordion({"View total": expensive_item}, lazy=True)+ ```- - An `Html` object.+ where `expensive_item` is the item to render, or a callable that+ returns the item to render."""def render_content(tab: object) -> str:diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.pyindex d3079c155c..347063182f 100644--- a/marimo/_plugins/stateless/audio.py+++ b/marimo/_plugins/stateless/audio.py@@ -18,24 +18,21 @@ def audio() -> Html:"""Render an audio file as HTML.- **Example.**+ Args:+ src: a path or URL to an audio file, bytes,+ or a file-like object opened in binary mode- ```python3- mo.audio(- src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Ivan_Ili%C4%87-Chopin_-_Prelude_no._1_in_C_major.ogg"- )+ Returns:+ An audio player as an `Html` object.- mo.audio(src="path/to/local/file.wav")- ```+ Example:+ ```python3+ mo.audio(+ src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Ivan_Ili%C4%87-Chopin_-_Prelude_no._1_in_C_major.ogg"+ )- **Args.**-- - `src`: a path or URL to an audio file, bytes,- or a file-like object opened in binary mode-- **Returns.**-- An audio player as an `Html` object.+ mo.audio(src="path/to/local/file.wav")+ ```"""resolved_src: Optional[str]diff --git a/marimo/_plugins/stateless/callout.py b/marimo/_plugins/stateless/callout.pyindex b3a8523a1a..afe1e4c594 100644--- a/marimo/_plugins/stateless/callout.py+++ b/marimo/_plugins/stateless/callout.py@@ -16,14 +16,12 @@ def callout() -> Html:"""Build a callout output.- **Args.**+ Args:+ value: A value to render in the callout+ kind: The kind of callout (affects styling).- - `value`: A value to render in the callout- - `kind`: The kind of callout (affects styling).-- **Returns.**-- - An HTML object.+ Returns:+ An HTML object."""return Html(build_stateless_plugin(diff --git a/marimo/_plugins/stateless/carousel.py b/marimo/_plugins/stateless/carousel.pyindex 97878784fa..9c30351c3b 100644--- a/marimo/_plugins/stateless/carousel.py+++ b/marimo/_plugins/stateless/carousel.py@@ -16,19 +16,16 @@ def carousel() -> Html:"""Create a carousel of items.- **Example.**+ Args:+ items: A list of items.- ```python3- mo.carousel([mo.md("..."), mo.ui.text_area()])- ```+ Returns:+ An `Html` object.- **Args.**-- - `items`: A list of items.-- **Returns.**-- - An `Html` object.+ Example:+ ```python3+ mo.carousel([mo.md("..."), mo.ui.text_area()])+ ```"""item_content = "".join([diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.pyindex 0b790cc63a..067f117e2f 100644--- a/marimo/_plugins/stateless/download.py+++ b/marimo/_plugins/stateless/download.py@@ -27,33 +27,30 @@ def download("""Show a download button for a url, bytes, or file-like object.- **Examples.**+ Args:+ data: The data to download. Can be a string (interpreted as+ a URL), bytes, or a file opened in binary mode.+ filename: The name of the file to download.+ If not provided, the name will be guessed from the data.+ mimetype: The mimetype of the file to download, for example,+ (e.g. "text/csv", "image/png"). If not provided,+ the mimetype will be guessed from the filename.- ```python- download_txt = mo.download(- data="Hello, world!".encode("utf-8"),- filename="hello.txt",- mimetype="text/plain",- )-- download_image = mo.download(- data=open("hello.png", "rb"),- )- ```-- **Args.**+ Returns:+ An `Html` object for a download button.- - `data`: The data to download. Can be a string (interpreted as- a URL), bytes, or a file opened in binary mode.- - `filename`: The name of the file to download.- If not provided, the name will be guessed from the data.- - `mimetype`: The mimetype of the file to download, for example,- (e.g. "text/csv", "image/png"). If not provided,- the mimetype will be guessed from the filename.-- **Returns.**+ Example:+ ```python+ download_txt = mo.download(+ data="Hello, world!".encode("utf-8"),+ filename="hello.txt",+ mimetype="text/plain",+ )- An `Html` object for a download button.+ download_image = mo.download(+ data=open("hello.png", "rb"),+ )+ ```"""# Convert to bytes right away since can only be read oncediff --git a/marimo/_plugins/stateless/mermaid.py b/marimo/_plugins/stateless/mermaid.pyindex e325ca9177..66b669254b 100644--- a/marimo/_plugins/stateless/mermaid.py+++ b/marimo/_plugins/stateless/mermaid.py@@ -8,33 +8,29 @@ from marimo._plugins.core.web_component import build_stateless_plugin@mddocdef mermaid(diagram: str) -> Html:- """- Render a diagram with Mermaid.-- **Examples.**-- ```python- diagram = '''- graph LR- A[Square Rect] -- Link text --> B((Circle))- A --> C(Round Rect)- B --> D{Rhombus}- C --> D- '''- mo.mermaid(diagram)- ```+ """Render a diagram with Mermaid.Mermaid is a tool for making diagrams such as flow charts and graphs. Seethe [Mermaid documentation](https://github.com/mermaid-js/mermaid#readme)for details.- **Args.**-- - `diagram`: a string containing a Mermaid diagram-- **Returns.**-- - An `Html` object.+ Args:+ diagram: a string containing a Mermaid diagram++ Returns:+ An `Html` object.++ Example:+ ```python+ diagram = '''+ graph LR+ A[Square Rect] -- Link text --> B((Circle))+ A --> C(Round Rect)+ B --> D{Rhombus}+ C --> D+ '''+ mo.mermaid(diagram)+ ```"""return Html(build_stateless_plugin(diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.pyindex 8ac65a8480..e83fcd86f8 100644--- a/marimo/_plugins/stateless/nav_menu.py+++ b/marimo/_plugins/stateless/nav_menu.py@@ -16,54 +16,50 @@ def nav_menu(*,orientation: Literal["horizontal", "vertical"] = "horizontal",) -> Html:- """- Navigation menu component.+ """Navigation menu component.This is useful for creating a navigation menu with hyperlinks,most used when creating multi-page applications, with`marimo.create_asgi_app` ([docs](https://docs.marimo.io/guides/deploying/programmatically.html)).- **Examples.**-- ```python- nav_menu = mo.nav_menu(- {- "/overview": "Overview",- "/sales": f"{mo.icon('lucide:shopping-cart')} Sales",- "/products": f"{mo.icon('lucide:package')} Products",- }- )- ```-- # You can also nest dictionaries to create submenus- ```python- nav_menu = mo.nav_menu(- {- "/overview": "Overview",- "Sales": {- "/sales": "Overview",- "/sales/invoices": {- "label": "Invoices",- "description": "View invoices",- },- "/sales/customers": {- "label": "Customers",- "description": "View customers",+ Args:+ menu: a dictionary of tab names to tab content;+ the content can also be nested dictionaries (one level deep)+ strings are interpreted as markdown++ Returns:+ An `Html` object.++ Example:+ ```python+ nav_menu = mo.nav_menu(+ {+ "/overview": "Overview",+ "/sales": f"{mo.icon('lucide:shopping-cart')} Sales",+ "/products": f"{mo.icon('lucide:package')} Products",+ }+ )+ ```++ # You can also nest dictionaries to create submenus+ ```python+ nav_menu = mo.nav_menu(+ {+ "/overview": "Overview",+ "Sales": {+ "/sales": "Overview",+ "/sales/invoices": {+ "label": "Invoices",+ "description": "View invoices",+ },+ "/sales/customers": {+ "label": "Customers",+ "description": "View customers",+ },},- },- }- )- ```-- **Args.**-- - `menu`: a dictionary of tab names to tab content;- the content can also be nested dictionaries (one level deep)- strings are interpreted as markdown-- **Returns.**-- - An `Html` object.+ }+ )+ ```"""menu_items = _build_and_validate_menu(menu)diff --git a/marimo/_plugins/stateless/plain_text.py b/marimo/_plugins/stateless/plain_text.pyindex 5a6779bdfe..be33d0aeb1 100644--- a/marimo/_plugins/stateless/plain_text.py+++ b/marimo/_plugins/stateless/plain_text.py@@ -11,13 +11,11 @@ from marimo._output.utils import create_styledef plain_text(text: str) -> Html:"""Text that's fixed-width, with spaces and newlines preserved.- **Args.**+ Args:+ text: text to output- - `text`: text to output-- **Returns.**-- An `Html` object representing the text.+ Returns:+ An `Html` object representing the text."""styles = create_style({"font-size": "12px"})img = h.pre(child=text, style=styles)diff --git a/marimo/_plugins/stateless/stat.py b/marimo/_plugins/stateless/stat.pyindex 765e8032e4..5f02671ed7 100644--- a/marimo/_plugins/stateless/stat.py+++ b/marimo/_plugins/stateless/stat.py@@ -21,18 +21,16 @@ def stat(Optionally include a label, caption, and direction.- **Args.**-- - `value`: the value to display- - `label`: the label to display- - `caption`: the caption to display- - `direction`: the direction of the statistic,- either `increase` or `decrease`- - `bordered`: whether to display a border around the statistic-- **Returns.**-- An `Html` object representing the statistic.+ Args:+ value: the value to display+ label: the label to display+ caption: the caption to display+ direction: the direction of the statistic,+ either `increase` or `decrease`+ bordered: whether to display a border around the statistic++ Returns:+ An `Html` object representing the statistic."""return Html(build_stateless_plugin(diff --git a/marimo/_plugins/stateless/tabs.py b/marimo/_plugins/stateless/tabs.pyindex 47b555cca6..301e4ed4f0 100644--- a/marimo/_plugins/stateless/tabs.py+++ b/marimo/_plugins/stateless/tabs.py@@ -10,37 +10,33 @@ from marimo._utils.deprecated import deprecated@mddoc@deprecated("mo.tabs is deprecated. Use mo.ui.tabs instead")def tabs(tabs: dict[str, object]) -> Html:- """- **Deprecated.**: Use `mo.ui.tabs` instead.+ """Deprecated: Use `mo.ui.tabs` instead.Tabs of UI elements.- **Examples.**-- ```python- tab1 = mo.vstack([- mo.ui.slider(1, 10),- mo.ui.text(),- mo.ui.date()- ]);- tab2 = mo.vstack([{- "slider": mo.ui.slider(1, 10),- "text": mo.ui.text(),- "date": mo.ui.date()- ]);- tabs = mo.tabs({- "Tab 1": tab1,- "Tab 2": tab2- })- ```-- **Args.**-- - `tabs`: a dictionary of tab names to tab content; strings are interpreted- as markdown-- **Returns.**-- - An `Html` object.+ Args:+ tabs: a dictionary of tab names to tab content; strings are interpreted+ as markdown++ Returns:+ An `Html` object.++ Example:+ ```python+ tab1 = mo.vstack([+ mo.ui.slider(1, 10),+ mo.ui.text(),+ mo.ui.date()+ ]);+ tab2 = mo.vstack([{+ "slider": mo.ui.slider(1, 10),+ "text": mo.ui.text(),+ "date": mo.ui.date()+ ]);+ tabs = mo.tabs({+ "Tab 1": tab1,+ "Tab 2": tab2+ })+ ```"""return tabs_impl(tabs)diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex c466a85a07..b9401866c1 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -38,8 +38,7 @@ class MiddlewareFactory(Protocol):class ASGIAppBuilder(abc.ABC):- """- Class for building ASGI applications.+ """Class for building ASGI applications.Methods:with_app(@@ -336,89 +335,85 @@ def create_asgi_app(include_code: bool = False,token: Optional[str] = None,) -> ASGIAppBuilder:- """- Public API to create an ASGI app that can serve multiple notebooks.+ """Public API to create an ASGI app that can serve multiple notebooks.This only works for application that are in Run mode.- **Examples.**-- You can create an ASGI app, and serve the application with a- server like `uvicorn`:-- ```python- import uvicorn-- builder = (- create_asgi_app()- .with_app(path="/app", root="app.py")- .with_app(path="/app2", root="app2.py")- .with_app(path="/", root="home.py")- )- app = builder.build()+ Args:+ quiet (bool, optional): Suppress standard out+ include_code (bool, optional): Include notebook code in the app+ token (str, optional): Auth token to use for the app.+ If not provided, an empty token is used.- if __name__ == "__main__":- uvicorn.run(app, port=8000)- ```+ Returns:+ ASGIAppBuilder: A builder object to create multiple ASGI apps- Or you can further integrate it with a FastAPI app:+ Example:+ You can create an ASGI app, and serve the application with a+ server like `uvicorn`:- ```python- import uvicorn- from fastapi import FastAPI- import my_middlewares- import my_routes+ ```python+ import uvicorn- app = FastAPI()+ builder = (+ create_asgi_app()+ .with_app(path="/app", root="app.py")+ .with_app(path="/app2", root="app2.py")+ .with_app(path="/", root="home.py")+ )+ app = builder.build()- builder = (- create_asgi_app()- .with_app(path="/app", root="app.py")- .with_app(path="/app2", root="app2.py")- )+ if __name__ == "__main__":+ uvicorn.run(app, port=8000)+ ```- # Add middlewares- app.add_middleware(my_middlewares.auth_middleware)+ Or you can further integrate it with a FastAPI app:+ ```python+ import uvicorn+ from fastapi import FastAPI+ import my_middlewares+ import my_routes- # Add routes- @app.get("/login")- async def root():- pass+ app = FastAPI()+ builder = (+ create_asgi_app()+ .with_app(path="/app", root="app.py")+ .with_app(path="/app2", root="app2.py")+ )- # Add the marimo app- app.mount("/", builder.build())+ # Add middlewares+ app.add_middleware(my_middlewares.auth_middleware)- if __name__ == "__main__":- uvicorn.run(app, port=8000)- ```- You may also want to dynamically load notebooks from a directory. To do- this, use the `with_dynamic_directory` method. This is useful if the- contents of the directory change often without requiring a server restart.+ # Add routes+ @app.get("/login")+ async def root():+ pass- ```python- import uvicorn- builder = create_asgi_app().with_dynamic_directory(- path="/notebooks", directory="./notebooks"- )- app = builder.build()+ # Add the marimo app+ app.mount("/", builder.build())- if __name__ == "__main__":- uvicorn.run(app, port=8000)- ```+ if __name__ == "__main__":+ uvicorn.run(app, port=8000)+ ```- **Args.**+ You may also want to dynamically load notebooks from a directory. To do+ this, use the `with_dynamic_directory` method. This is useful if the+ contents of the directory change often without requiring a server restart.- - quiet (bool, optional): Suppress standard out- - include_code (bool, optional): Include notebook code in the app- - token (str, optional): Auth token to use for the app.- If not provided, an empty token is used.+ ```python+ import uvicorn- **Returns.**+ builder = create_asgi_app().with_dynamic_directory(+ path="/notebooks", directory="./notebooks"+ )+ app = builder.build()- - ASGIAppBuilder: A builder object to create multiple ASGI apps+ if __name__ == "__main__":+ uvicorn.run(app, port=8000)+ ```"""from starlette.applications import Starlettefrom starlette.responses import RedirectResponse