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
feat: mo.routes() (#1356)
Myles Scolnickb71e1d9aa258
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex f718cfc1df..7d69847f6f 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -6,7 +6,6 @@ Provide a concise summary of what this pull request is addressing.If this PR fixes any issues, list them here by number (e.g., Fixes #123).-->-## 🔍 Description of Changes<!--diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 3de658f0c1..f8e007e11a 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -11,7 +11,7 @@ repos:hooks:- id: markdownlint-fixargs: [-c, configs/.markdownlint.yaml, --fix]- exclude: marimo/_tutorials/.*\.md+ exclude: ^marimo/_tutorials/.*\.md- repo: https://github.com/crate-ci/typosrev: v1.21.0diff --git a/configs/.markdownlint.yaml b/configs/.markdownlint.yamlindex f0ff114568..774c3dc528 100644--- a/configs/.markdownlint.yaml+++ b/configs/.markdownlint.yaml@@ -18,3 +18,5 @@ MD001: falseMD040: false# ol-prefixMD029: false+# no-trailing-punctuation+MD026: falsediff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.mdindex 3d6a988fd5..245db24dff 100644--- a/docs/api/layouts/index.md+++ b/docs/api/layouts/index.md@@ -11,6 +11,7 @@justifylazynav_menu+ routessidebarstackstree@@ -37,6 +38,7 @@ them but just render their children in a certain way.marimo.leftmarimo.nav_menumarimo.right+ marimo.routesmarimo.sidebarmarimo.treemarimo.vstackdiff --git a/docs/api/layouts/routes.md b/docs/api/layouts/routes.mdnew file mode 100644index 0000000000..385e7e4c6e--- /dev/null+++ b/docs/api/layouts/routes.md@@ -0,0 +1,41 @@+# Routes++```{eval-rst}+.. marimo-embed::+ :size: medium++ @app.cell+ def __():+ mo.sidebar(+ [+ mo.md("# marimo"),+ mo.nav_menu(+ {+ "#/": 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",+ ),+ ]+ )+ return++ @app.cell+ def __():+ mo.routes({+ "#/": mo.md("# Home"),+ "#/about": mo.md("# About"),+ "#/contact": mo.md("# Contact"),+ mo.routes.CATCH_ALL: mo.md("# Home"),+ })+ return+```++```{eval-rst}+.. autofunction:: marimo.routes+```diff --git a/docs/api/layouts/sidebar.md b/docs/api/layouts/sidebar.mdindex c41f6582a1..c28065369b 100644--- a/docs/api/layouts/sidebar.md+++ b/docs/api/layouts/sidebar.md@@ -11,9 +11,9 @@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",+ "#/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",diff --git a/docs/guides/deploying/deploying_marimo_cloud.md b/docs/guides/deploying/deploying_marimo_cloud.mdindex 5095431ff8..7f8ff5c922 100644--- a/docs/guides/deploying/deploying_marimo_cloud.md+++ b/docs/guides/deploying/deploying_marimo_cloud.md@@ -8,7 +8,6 @@ Marimo Cloud is currently in beta: if you'd like access, email us at[[email protected]](mailto:[email protected]) or book time on [ourcalendar](calendly.com/akshay-marimo) and we'll onboard you very quickly.-## Marimo CloudMarimo Cloud seamlessly augments local development on marimo notebooks with@@ -23,7 +22,7 @@ Today, marimo cloud has two main features:We have many more features planned for the near future, and **big ideas** onhow Marimo Cloud can supercharge the entire lifecycle of working with and-experimenting on data, from small workloads to very large ones as well.+experimenting on data, from small workloads to very large ones as well.## Reach out to us!diff --git a/docs/guides/deploying/deploying_ploomber.md b/docs/guides/deploying/deploying_ploomber.mdindex d56fcd2e1f..f0fbd9b4cb 100644--- a/docs/guides/deploying/deploying_ploomber.md+++ b/docs/guides/deploying/deploying_ploomber.md@@ -2,4 +2,4 @@For production deployments, you can use Ploomber Cloud. It allows you to deploymarimo in a secure and scalable way. See-[deployment instructions here](https://docs.cloud.ploomber.io/en/latest/apps/marimo.html)\ No newline at end of file+[deployment instructions here](https://docs.cloud.ploomber.io/en/latest/apps/marimo.html)diff --git a/docs/guides/deploying/index.md b/docs/guides/deploying/index.mdindex 430c75a2d8..6bda6ddd30 100644--- a/docs/guides/deploying/index.md+++ b/docs/guides/deploying/index.md@@ -37,7 +37,6 @@ WASM notebooks support most but not all Python features and packages. See ourFor a turnkey cloud solution, try [Marimo Cloud](/guides/deploying/deploying_marimo_cloud.md).```-## Programmatically running the marimo backendWhen deploying marimo notebooks, you can run the marimo backend programmatically. This allows you to customize the backend to your needs and deploy it in your own environment.diff --git a/frontend/package.json b/frontend/package.jsonindex 0e729a7f25..ab14044832 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -101,6 +101,7 @@"lz-string": "^1.5.0","mermaid": "^10.9.0","partysocket": "1.0.1",+ "path-to-regexp": "^6.2.2","plotly.js": "^2.32.0","pyodide": "^0.25.1","react-arborist": "^3.4.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 244a06ef0e..d18d314aba 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -269,6 +269,9 @@ dependencies:partysocket:specifier: 1.0.1version: 1.0.1+ path-to-regexp:+ specifier: ^6.2.2+ version: 6.2.2plotly.js:specifier: ^2.32.0version: 2.32.0([email protected])@@ -15139,6 +15142,10 @@ packages:resolution: {integrity: sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==}dev: true+ resolution: {integrity: sha512-GQX3SSMokngb36+whdpRXE+3f9V8UzyAorlYvOGx87ufGHehNTn5lCxrKtLyZ4Yl/wEKnNnr98ZzOwwDZV5ogw==}+ dev: false+resolution: {integrity: sha512-S4eENJz1pkiQn9Znv33Q+deTOKmbl+jj1Fl+qiP/vYezj+S8x+J3Uo0ISrx/QoEvIlOaDWJhPaRd1flJ9HXZqg==}engines: {node: '>=0.10.0'}diff --git a/frontend/src/plugins/layout/RoutesPlugin.tsx b/frontend/src/plugins/layout/RoutesPlugin.tsxnew file mode 100644index 0000000000..1425a382a1--- /dev/null+++ b/frontend/src/plugins/layout/RoutesPlugin.tsx@@ -0,0 +1,73 @@+/* Copyright 2024 Marimo. All rights reserved. */+import React, { PropsWithChildren, useEffect, useMemo, useState } from "react";++import { z } from "zod";+import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";+import { TinyRouter } from "@/utils/routes";+import useEvent from "react-use-event-hook";++interface Data {+ /**+ * Route paths to render.+ */+ routes: string[];+}++export class RoutesPlugin implements IStatelessPlugin<Data> {+ tagName = "marimo-routes";++ validator = z.object({+ routes: z.array(z.string()),+ });++ render(props: IStatelessPluginProps<Data>): JSX.Element {+ return <RoutesComponent {...props.data}>{props.children}</RoutesComponent>;+ }+}++const RoutesComponent = ({+ routes,+ children,+}: PropsWithChildren<Data>): JSX.Element => {+ const childCount = React.Children.count(children);+ if (childCount !== routes.length) {+ throw new Error(+ `Expected ${routes.length} children, but got ${childCount}`,+ );+ }++ const router = useMemo(() => new TinyRouter(routes), [routes]);+ const [matched, setMatched] = useState<string | null>(() => {+ const match = router.match(window.location);+ return match ? match[1] : null;+ });++ const handleFindMatch = useEvent((location: Location) => {+ const match = router.match(location);+ setMatched(match ? match[1] : null);+ });++ useEffect(() => {+ // Listen for route changes+ const listener = (e: PopStateEvent | HashChangeEvent) => {+ handleFindMatch(window.location);+ };+ window.addEventListener("hashchange", listener);+ window.addEventListener("popstate", listener);+ return () => {+ window.removeEventListener("hashchange", listener);+ window.removeEventListener("popstate", listener);+ };+ }, [handleFindMatch]);++ if (!matched) {+ // eslint-disable-next-line react/jsx-no-useless-fragment+ return <></>;+ }++ const matchedIndex = routes.indexOf(matched);+ const child = React.Children.toArray(children)[matchedIndex];++ // eslint-disable-next-line react/jsx-no-useless-fragment+ return <>{child}</>;+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 7a5fa77a66..b2fc75e979 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -42,6 +42,7 @@ import { AnyWidgetPlugin } from "./impl/anywidget/AnyWidgetPlugin";import { LazyPlugin } from "./layout/LazyPlugin";import { NavigationMenuPlugin } from "@/plugins/layout/NavigationMenuPlugin";import { initializeSidebarElement } from "./core/sidebar-element";+import { RoutesPlugin } from "./layout/RoutesPlugin";// List of UI pluginsexport const UI_PLUGINS: Array<IPlugin<any, unknown>> = [@@ -81,11 +82,12 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [new CarouselPlugin(),new DownloadPlugin(),new JsonOutputPlugin(),+ new MermaidPlugin(),+ new NavigationMenuPlugin(),new ProgressPlugin(),+ new RoutesPlugin(),new StatPlugin(),new TexPlugin(),- new MermaidPlugin(),- new NavigationMenuPlugin(),];export function initializePlugins() {diff --git a/frontend/src/utils/__tests__/routes.test.ts b/frontend/src/utils/__tests__/routes.test.tsnew file mode 100644index 0000000000..56ba4fc8ab--- /dev/null+++ b/frontend/src/utils/__tests__/routes.test.ts@@ -0,0 +1,46 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect } from "vitest";+import { TinyRouter } from "../routes";++describe("TinyRouter.match", () => {+ it("should return the correct match and template for a given location", () => {+ const templates = ["/path1", "/path2"];+ const router = new TinyRouter(templates);++ const location1 = { hash: "", pathname: "/path1" } as Location;+ const location2 = { hash: "", pathname: "/path2" } as Location;++ expect(router.match(location1)).toEqual([expect.any(Object), "/path1"]);+ expect(router.match(location2)).toEqual([expect.any(Object), "/path2"]);+ });++ it("should return false if no match is found", () => {+ const templates = ["/path1", "/path2"];+ const router = new TinyRouter(templates);++ const location = { hash: "", pathname: "/path3" } as Location;++ expect(router.match(location)).toBe(false);+ });++ it("should return the correct match for hash locations", () => {+ const templates = ["#/path1", "#/path2"];+ const router = new TinyRouter(templates);++ const location = { hash: "#/path1", pathname: "" } as Location;++ expect(router.match(location)).toEqual([expect.any(Object), "#/path1"]);+ });++ it("order should matter for nested routes", () => {+ const templates = ["/path1", "/path1/nested"];+ const router = new TinyRouter(templates);++ const location = { hash: "", pathname: "/path1/nested" } as Location;++ expect(router.match(location)).toEqual([+ expect.any(Object),+ "/path1/nested",+ ]);+ });+});diff --git a/frontend/src/utils/routes.ts b/frontend/src/utils/routes.tsnew file mode 100644index 0000000000..8889befddb--- /dev/null+++ b/frontend/src/utils/routes.ts@@ -0,0 +1,31 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { match, Match, MatchFunction } from "path-to-regexp";++export class TinyRouter {+ private routes: Array<{+ template: string;+ pathFunction: MatchFunction;+ }>;++ constructor(templates: string[]) {+ this.routes = templates.map((template) => {+ return {+ template,+ pathFunction: match(template),+ };+ });+ }++ match(location: Location): [Match, template: string] | false {+ for (const { pathFunction, template } of this.routes) {+ const match =+ pathFunction(location.hash) || pathFunction(location.pathname);+ if (match) {+ return [match, template];+ }+ }++ return false;+ }+}diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 6710a4d871..80ca54c687 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -132,10 +132,12 @@ export default defineConfig({},},},- headers: {- "Cross-Origin-Opener-Policy": "same-origin",- "Cross-Origin-Embedder-Policy": "require-corp",- },+ headers: isPyodide+ ? {+ "Cross-Origin-Opener-Policy": "same-origin",+ "Cross-Origin-Embedder-Policy": "require-corp",+ }+ : {},},define: {"import.meta.env.VITE_MARIMO_VERSION": process.env.VITE_MARIMO_VERSIONdiff --git a/marimo/__init__.py b/marimo/__init__.pyindex 65e626dc8f..cba859b153 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -49,6 +49,7 @@ __all__ = ["refs","right","running_in_notebook",+ "routes","sidebar","stat","state",@@ -86,6 +87,7 @@ from marimo._plugins.stateless.mermaid import mermaidfrom marimo._plugins.stateless.nav_menu import nav_menufrom marimo._plugins.stateless.pdf import pdffrom marimo._plugins.stateless.plain_text import plain_text+from marimo._plugins.stateless.routes import routesfrom marimo._plugins.stateless.sidebar import sidebarfrom marimo._plugins.stateless.stat import statfrom marimo._plugins.stateless.style import stylediff --git a/marimo/_plugins/stateless/routes.py b/marimo/_plugins/stateless/routes.pynew file mode 100644index 0000000000..39848bbbb8--- /dev/null+++ b/marimo/_plugins/stateless/routes.py@@ -0,0 +1,119 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, Callable, Coroutine, Final, Union++from marimo._output.formatting import as_html+from marimo._output.hypertext import Html+from marimo._output.rich_help import mddoc+from marimo._plugins.stateless import lazy+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.++ 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, use+ 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.++ **Returns.**++ - An `Html` object.+ """++ _name: Final[str] = "marimo-routes"++ CATCH_ALL = "/(.*)"+ DEFAULT = "/"++ def __init__(+ self,+ routes: dict[+ str,+ Union[+ Callable[[], object],+ Callable[[], Coroutine[None, None, object]],+ object,+ ],+ ],+ ) -> None:+ # For functions, wrap in lazy+ children: list[Html] = []+ for _, content in routes.items():+ if callable(content):+ children.append(lazy.lazy(content))+ else:+ children.append(as_html(content))++ self._children = children+ text = "".join([child.text for child in children])++ super().__init__(+ component_name=self._name,+ initial_value="",+ label=None,+ args={+ "routes": list(routes.keys()),+ },+ on_change=None,+ slotted_html=text,+ )++ def _convert_value(self, value: str) -> str:+ return value++ # Not supported+ def batch(self, *args: Any, **kwargs: Any) -> Any:+ del args, kwargs+ raise TypeError(".batch() is not supported on mo.sidebar")++ def center(self, *args: Any, **kwargs: Any) -> Html:+ del args, kwargs+ raise TypeError(".center() is not supported on mo.sidebar")++ def right(self, *args: Any, **kwargs: Any) -> Html:+ del args, kwargs+ raise TypeError(".right() is not supported on mo.sidebar")++ def left(self, *args: Any, **kwargs: Any) -> Html:+ del args, kwargs+ raise TypeError(".left() is not supported on mo.sidebar")++ def callout(self, *args: Any, **kwargs: Any) -> Html:+ del args, kwargs+ raise TypeError(".callout() is not supported on mo.sidebar")++ def style(self, *args: Any, **kwargs: Any) -> Html:+ del args, kwargs+ raise TypeError(".style() is not supported on mo.sidebar")diff --git a/marimo/_smoke_tests/routes.py b/marimo/_smoke_tests/routes.pynew file mode 100644index 0000000000..c5b4be8eb8--- /dev/null+++ b/marimo/_smoke_tests/routes.py@@ -0,0 +1,152 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.5.2"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ mo.sidebar(+ [+ mo.md("# marimo"),+ mo.nav_menu(+ {+ "#/home": f"{mo.icon('lucide:home')} Home",+ "#/about": f"{mo.icon('lucide:user')} About",+ "#/sales": f"{mo.icon('lucide:bar-chart')} Sales",+ },+ orientation="vertical",+ ),+ ]+ )+ return+++def __(mo):+ def render_home():+ return mo.md("""+ <p align="center">+ <img src="https://github.com/marimo-team/marimo/raw/main/docs/_static/marimo-logotype-thick.svg">+ </p>++ <p align="center">+ <em>A reactive Python notebook that's reproducible, git-friendly, and deployable as scripts or apps.</em>++ <p align="center">+ <a href="https://docs.marimo.io" target="_blank"><strong>Docs</strong></a> ·+ <a href="https://discord.gg/JE7nhX6mD8" target="_blank"><strong>Discord</strong></a> ·+ <a href="https://github.com/marimo-team/marimo/tree/main/examples" target="_blank"><strong>Examples</strong></a>+ </p>++ <p align="center">+ <a href="https://pypi.org/project/marimo/"><img src="https://img.shields.io/pypi/v/marimo?color=%2334D058&label=pypi" /></a>+ <a href="https://anaconda.org/conda-forge/marimo"/img><img src="https://img.shields.io/conda/vn/conda-forge/marimo.svg"></img></a>+ <a href="https://github.com/marimo-team/marimo/blob/main/LICENSE"><img src="https://img.shields.io/pypi/l/marimo"></img></a>+ </p>++ """)+ return render_home,+++def __(mo):+ def render_about():+ return mo.md(+ """+ # About++ **marimo** is a reactive Python notebook: run a cell or interact with a UI+ element, and marimo automatically runs dependent cells, keeping code and outputs+ consistent. marimo notebooks are stored as pure Python, executable as scripts,+ and deployable as apps.++ **Highlights**.++ - **reactive**: run a cell, and marimo automatically runs all dependent cells+ - **interactive**: bind sliders, tables, plots, and more to Python — no callbacks required+ - **reproducible**: no hidden state, deterministic execution+ - **executable**: execute as a Python script, parametrized by CLI args+ - **shareable**: deploy as an interactive web app, or run in the browser via WASM+ - **git-friendly**: stored as `.py` files+++ ## Community++ We're building a community. Come hang out with us!++ - 🌟 [Star us on GitHub](https://github.com/marimo-team/marimo)+ - 💬 [Chat with us on Discord](https://discord.gg/JE7nhX6mD8)+ - 📧 [Subscribe to our Newsletter](https://marimo.io/newsletter)+ - ☁️ [Join our Cloud Waitlist](https://marimo.io/cloud)+ - ✏️ [Start a GitHub Discussion](https://github.com/marimo-team/marimo/discussions)+ - 🐦 [Follow us on Twitter](https://twitter.com/marimo_io)+ - 🕴️ [Follow us on LinkedIn](https://www.linkedin.com/company/marimo-io)++ """+ )+ return render_about,+++def __(mo):+ slider = mo.ui.slider(0, 100, value=20)+ return slider,+++def __(mo, slider):+ def render_sales():+ import altair as alt+ import pandas as pd+ import numpy as np++ num = slider.value+ x = np.arange(num)+ y = np.random.randint(0, 100, num)+ df = pd.DataFrame({"x": x, "y": y})++ chart = (+ alt.Chart(df)+ .mark_bar()+ .encode(+ x="x",+ y="y",+ )+ )++ return mo.md(+ f"""+ # Sales++ Number of points: {slider}++ {mo.as_html(mo.ui.altair_chart(chart))}+ """+ )+ return render_sales,+++def __(mo, render_about, render_home, render_sales):+ mo.routes(+ {+ "#/home": render_home,+ "#/about": render_about,+ "#/sales": render_sales,+ mo.routes.CATCH_ALL: render_home,+ }+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/stateless/test_lazy.py b/tests/_plugins/stateless/test_lazy.pyindex 89cbe27254..751ab5856b 100644--- a/tests/_plugins/stateless/test_lazy.py+++ b/tests/_plugins/stateless/test_lazy.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import gcfrom typing import Anyfrom marimo._runtime.context import get_context@@ -11,6 +12,7 @@ from tests.conftest import ExecReqProviderdef get_only_function() -> Function[Any, Any]:+ gc.collect()context: RuntimeContext = get_context()assert len(context.function_registry.namespaces.values()) == 1first_namespace = next(iter(context.function_registry.namespaces.values()))diff --git a/tests/_plugins/stateless/test_routes.py b/tests/_plugins/stateless/test_routes.pynew file mode 100644index 0000000000..6973ef6de2--- /dev/null+++ b/tests/_plugins/stateless/test_routes.py@@ -0,0 +1,80 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import gc++from marimo._runtime.context import get_context+from marimo._runtime.context.types import RuntimeContext+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++async def test_routes_lazy(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ mo.routes(+ {+ "#/": lambda: 42,+ "#/about": lambda: 43,+ "#/contact": lambda: 44,+ mo.routes.CATCH_ALL: lambda: 45,+ }+ )+ """+ ),+ ]+ )++ gc.collect()+ context: RuntimeContext = get_context()+ # 4 functions, 1 for each route+ assert len(context.function_registry.namespaces.values()) == 4++ expected_results = [+ "<span>42</span>",+ "<span>43</span>",+ "<span>44</span>",+ "<span>45</span>",+ ]++ for i, expected in enumerate(context.function_registry.namespaces):+ function = next(+ iter(+ context.function_registry.namespaces[+ expected+ ].functions.values()+ )+ )+ res = await function({})+ assert res.html == expected_results[i]+ assert function.name == "load"+++async def test_routes_non_lazy(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ routes = mo.routes(+ {+ "#/": 42,+ mo.routes.CATCH_ALL: 45,+ }+ )+ """+ ),+ ]+ )++ context: RuntimeContext = get_context()+ # No functions, all routes are non-lazy+ assert len(context.function_registry.namespaces.values()) == 0++ routes = k.globals["routes"]+ children = "<span>42</span>" "<span>45</span>"+ assert children in routes.text+ assert "data-routes='["#/", "/(.*)"]'" in routes.text