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: new file format documentation (#4497)
Dylan Madisettif90b254d3fa6
diff --git a/docs/guides/editor_features/watching.md b/docs/guides/editor_features/watching.mdindex de7ecaa99b..4c8d0e9f07 100644--- a/docs/guides/editor_features/watching.md+++ b/docs/guides/editor_features/watching.md@@ -11,6 +11,49 @@ have the changes automatically reflected in your browser.For better performance, install [watchdog](https://pypi.org/project/watchdog/).Without watchdog, marimo resorts to polling.+## marimo's file format++!!! tip "File format tutorial"++ Run `marimo tutorial fileformat` at the command line for a full guide.++marimo stores notebooks as Python cells. Cells are stored as functions,+decorated with`@app.cell`; you can optionally give cells names in the editor+UI or by editing the notebook file.++```python+def memorable_cell_name(auto, determined, references): # signature denotes cell inputs+ computed_value = auto + determined + references+ "hello!" # final statement are outputted+ return computed_value # return denotes cell outputs+```++!!! note "Cell signature and returns"++ Don't worry about maintaining the signatures of cells and their return+ values; marimo will handle this for you.++You may also expose imports, and top-level functions and classes in your+notebook. Functions must be decorated with `@app.function`, and classes with+`app.class_definition`. These functions and classes must be pure, closing over+only other pure functions and classes or imports and constants defined in+an `app.setup` with block:++For more details see the [library guide](../reusing_functions.md).++```python+with app.setup:+ CONSTANT: int = 1+ import marimo as mo++def my_function(x): ...+[email protected]_definition+class MyClass: ...+```+## `marimo edit --watch`When you run `marimo edit` with the `--watch` flag, the marimo server@@ -18,21 +61,18 @@ will open your notebook in the browser and watch the underlying notebookfile for changes. When you make changes to the notebook file, they will bestreamed to the marimo editor in the browser.-By default, synced code will not be executed automatically, with cells marked as stale instead.-Run all stale cells with the marimo editor's "Run" button, or the [`runStale`-hotkey](hotkeys.md), to see the new outputs.+By default, synced code will not be executed automatically, with cells marked+as stale instead. Run all stale cells with the marimo editor's "Run" button, or+the [`runStale` hotkey](hotkeys.md), to see the new outputs.-If you want to run all affected cells automatically when you save, change the `runtime` config in your `pyproject.toml` file.+If you want to run all affected cells automatically when you save, change the+`runtime` config in your `pyproject.toml` file.```toml[tool.marimo.runtime]watcher_on_save = "autorun"```-!!! note "Cell signature and returns"- Don't worry about maintaining the signatures of cells and their return- values; marimo will handle this for you.-## `marimo run --watch`When you run a notebook with the `--watch` flag, whenever the file watcher@@ -50,14 +90,16 @@ Guide](module_autoreloading.md)## Watching for data changes!!! note- Support for watching data files and automatically refreshing cells that depend on them is coming soon. Follow along at <https://github.com/marimo-team/marimo/issues/3258>+ Support for watching data files and automatically refreshing cells that+ depend on them is coming soon. Follow along at+ <https://github.com/marimo-team/marimo/issues/3258>## Hot-reloading WebAssembly notebooks-Follow these steps to develop a notebook using your own editor while-previewing it as a [WebAssembly notebook](../wasm.md) in the browser. This lets-you take advantage of local development tools while seeing the notebook as it-appears when deployed as a WebAssembly notebook.+Follow these steps to develop a notebook using your own editor while previewing+it as a [WebAssembly notebook](../wasm.md) in the browser. This lets you take+advantage of local development tools while seeing the notebook as it appears+when deployed as a WebAssembly notebook.```bash# in one terminal, start a watched edit (or run) sessiondiff --git a/docs/guides/index.md b/docs/guides/index.mdindex 50eea9c1c8..ec39c3f56b 100644--- a/docs/guides/index.md+++ b/docs/guides/index.md@@ -17,11 +17,12 @@ These guides cover marimo's core concepts.| [Understanding errors](understanding_errors/index.md) | Understanding marimo's constraints on notebook code || [Working with data](working_with_data/index.md) | Using SQL cells, no-code dataframe, and reactive plots || [Package reproducibility](package_reproducibility.md) | Making notebooks reproducible down to the packages |-| [Generate with AI](generate_with_ai/index.md) | Generate notebooks with AI |+| [Generate with AI](generate_with_ai/index.md) | Generate notebooks with AI || [Editor features](editor_features/index.md) | View variables, dataframe schemas, docstrings, and more || [Using your own editor](editor_features/watching.md) | Edit notebooks in your own editor and stream changes back to the browser || [Apps](apps.md) | Running notebooks as apps || [Scripts](scripts.md) | Running notebooks as scripts |+| [Reusing functions and classes](reusing_functions.md) | Importing functions and classes defined in marimo notebooks || [Tests](testing/index.md) | Running unit tests in notebooks || [Export notebooks](exporting.md) | Exporting notebooks to HTML, ipynb, flat scripts, and more || [Publish to the web](publishing/index.md) | Edit and publish notebooks on the web |diff --git a/docs/guides/reusing_functions.md b/docs/guides/reusing_functions.mdnew file mode 100644index 0000000000..3624f9e077--- /dev/null+++ b/docs/guides/reusing_functions.md@@ -0,0 +1,143 @@+# Importing Functions and Classes Defined in Marimo Notebooks++You can import top-level functions and classes defined in a marimo notebook+into other Python scripts or notebooks using normal Python syntax, as long as+your definitions satisfy the simple criteria described on this page. This makes+your notebook code modular and reusable, testable, and easier to edit in text editors+of your choice.++## Overview++For a function or class to be saved at the top level of the notebook file, it must+meet the following **criteria**:++1. The cell must define just a single function or class.+2. The defined function or class can only refer to symbols defined in the+ [setup cell](#create-a-setup-cell), or to other top-level symbols.+++### Example++/// marimo-embed+```python+def my_utility_function(x):+ return x * 2+[email protected]_definition+class DataProcessor:+ def __init__(self, data):+ self.data = data++ def process(self):+ return [x * 2 for x in self.data]+```+///++In another script or notebook++```python+from my_notebook import my_utility_function, DataProcessor+```++## Creating a top-level function++### 1. Create a setup cell++First, add a **setup cell** to your notebook for imports that your functions or+classes will need:++```python+import numpy as np+```++To add a setup cell in the editor, use the General menu and select "Add setup cell" (💠).++Setup cells are guaranteed to run before all other cells.++### 2. Define your function++Define a single function in a cell. If the+[criteria](overview) for top-level+functions are met, a marker in the bottom right will indicate that it is a+reusable function.++!!! note++ Functions can only reference symbols defined in the setup cell. If a+ function cannot be serialized top-level, the marker in the+ bottom right will provide a description why.++/// marimo-embed+```python+with app.setup:+ import numpy as np++def calculate_statistics(data):+ """Calculate basic statistics for a dataset"""+ return {+ "mean": np.mean(data),+ "median": np.median(data),+ "std": np.std(data)+ }+```+///++Under the hood, marimo decorates top-level functions with `@app.function`,+which you can use to define your own top-level functions if you are editing a+notebook file directly.++### 3. Reuse your definitions++Now you can import your function in other notebooks or Python scripts:++```python+# In another_script.py+from my_notebook import calculate_statistics++data = [1, 2, 3, 4, 5]+stats = calculate_statistics(data)+print(stats)+```++## Class definitions++Classes are also serialized top-level if they meet the [criteria](overview).+Under the hood, marimo decorates top-level classes with+`@app.class_definition`, which you can use if you are editing your notebook+file directly:++```python[email protected]_definition+class DataProcessor:+ def __init__(self, data):+ self.data = data++ def normalize(self):+ return (self.data - np.mean(self.data)) / np.std(self.data)+```++## Best practices++- Use setup cells for immediate, widely used imports+- Keep function dependencies limited to setup-cell references, or other top-level declarations.+- Use descriptive names for your functions+- Add docstrings to document your functions' behavior++!!! tip++ Top-level symbols can reference other top-level symbols.+++## Limitations++- Functions cannot depend on variables defined in regular cells+- Like other cells, cyclic dependencies between functions are not allowed++## Learn more++For more detailed information about marimo's file format and features, check+out our [documentation on using your own+editor](https://docs.marimo.io/guides/editor_features/watching/) or view our+[file format tutorial](https://marimo.app/?slug=8n55fd).diff --git a/marimo/_tutorials/fileformat.py b/marimo/_tutorials/fileformat.pyindex cec3421a0c..cfbd7802a8 100644--- a/marimo/_tutorials/fileformat.py+++ b/marimo/_tutorials/fileformat.py@@ -1,108 +1,105 @@-# Copyright 2024 Marimo. All rights reserved.+# Copyright 2025 Marimo. All rights reserved+import marimo-__generated_with = "0.1.69"+__generated_with = "0.12.8"app = marimo.App()-[email protected](hide_code=True)-def __(intro, mo):- mo.md(intro)- return--[email protected](hide_code=True)-def __(mo):- mo.accordion(- {- "Tip: hide this tutorial's code": (- """- Click the app window icon in the bottom-right to hide this app's code,- or use the "fold code" shortcut to fold all code cells.- """- )- }- )- return+with app.setup:+ import dataclasses+ import random[email protected](hide_code=True)-def __(example_program, mo):- mo.md(example_program)- return--[email protected](hide_code=True)-def __(file_contents, mo):- mo.md(file_contents)- return+def _():+ import marimo as mo+ return (mo,)@app.cell(hide_code=True)-def __(mo):+def _(mo):mo.md(- """- ## Properties+ r"""+ # File Format- marimo's file format was designed to be easy to read and easy- to work with, while also serving the needs of the marimo library. You can- even edit the generated file's cells directly, using your favorite text- editor, and format the file with your favorite code formatter.+ marimo apps are stored as pure Python files.- We explain some properties of marimo's file format below.+ These files are:++ - 🤖 legible for both humans and machines+ - ✏️ formattable using your tool of choice+ - ➕ easily versioned with git, producing small diffs+ - 🐍 usable as Python scripts, with UI elements taking their default values+ - 🧩 modular, exposing functions and classes that can be imported from the notebook""")return@app.cell(hide_code=True)-def __(mo, properties):- mo.accordion(properties)- return+def _(mo):+ mo.md(+ """+ ## Example+ Consider a marimo notebook with the following four cells.[email protected](hide_code=True)-def __():- intro = """- # File Format+ First cell:+ ```python3+ print(text.value)+ ```- marimo apps are stored as pure Python files.+ Second cell:+ ```python3+ def say_hello(name="World"):+ return f"Hello, {name}!"+ ```- These files are:+ Third cell:+ ```python3+ text = mo.ui.text(value=say_hello())+ text+ ```- - easily versioned with git, producing small diffs- - legible for both humans and machines- - formattable using your tool of choice- - usable as Python scripts, with UI elements taking their default values- """- return intro,+ Fourth cell:+ ```python3+ import marimo as mo+ ```+ """+ )+ return@app.cell(hide_code=True)-def __(mo):- file_contents = f"""- For the above example, marimo would generate the following file+def _(mo):+ mo.md(+ """+ For the above example, marimo would generate the following filecontents:```python3import marimo- __generated_with = "{mo.__version__}"+ __generated_with = "0.0.0"app = marimo.App()@app.cell- def __(text):+ def _(text):print(text.value)return+ @app.function+ def say_hello(name="World"):+ return f"Hello, {name}!"+@app.cell- def __(mo):+ def _(mo):text = mo.ui.text(value="Hello, World!")text- return text,+ return (text,)@app.cell- def __():+ def _():import marimo as moreturn mo,@@ -111,57 +108,52 @@ def __(mo):```As you can see, this is _pure Python_. This is part of the reason why- marimo's generated files are **git-friendly**: small changes made using- the marimo editor result in small changes to the file that marimo+ marimo's generated files are **git-friendly**: small changes made using+ the marimo editor result in small changes to the file that marimogenerates.- """- return file_contents,-[email protected](hide_code=True)-def __():- example_program = """- ## Example+ Moreover, the cell defining a single pure function `say_hello` was saved "top-level" in the notebook file, making it possible for you to import it into other Python files or notebooks.+ """+ )+ return- Consider a marimo notebook with the following three cells.- First cell:- ```python3- print(text.value)- ```[email protected](hide_code=True)+def _(mo):+ mo.md(+ """+ ## Properties- Second cell:- ```python3- text = mo.ui.text(value="Hello, World!")- text- ```+ marimo's file format was designed to be easy to read and easy+ to work with, while also serving the needs of the marimo library. You can+ even edit the generated file's cells directly, using your favorite text+ editor, and format the file with your favorite code formatter.- Third cell:- ```python3- import marimo as mo- ```- """- return example_program,+ We explain some properties of marimo's file format below.+ """+ )+ return@app.cell(hide_code=True)-def __():- properties = {- "Cells are functions": """- In the `dataflow` tutorial, we saw that cells are like functions mapping- their refs (the global variables they uses but don't define) to their- defs (the global variables they define). The generated code makes this+def _(mo):+ mo.accordion(+ {+ "Cells are functions": """+ In the `dataflow` tutorial, we saw that cells are like functions mapping+ their refs (the global variables they uses but don't define) to their+ defs (the global variables they define). The generated code makes thisanalogy explicit.- In the generated code, there is a function for each cell. The arguments- of the function are the cell's refs , and its returned variables are+ In the generated code, there is a function for each cell. The arguments+ of the function are the cell's refs , and its returned variables areits defs.For example, the code```python3@app.cell- def __(mo):+ def _(mo):text = mo.ui.text(value="Hello, World!")textreturn text,@@ -174,43 +166,43 @@ def __():```python3@app.cell- def __():+ def _():import marimo as moreturn mo,```- says that the cell doesn't depend on any other cells (its argument list- is empty), though it does create the variable `mo` which the previous+ says that the cell doesn't depend on any other cells (its argument list+ is empty), though it does create the variable `mo` which the previouscell requires as input.""",- "Cells are stored in presentation order": """- Cells are stored in the order that they are arranged in the marimo+ "Cells are stored in presentation order": """+ Cells are stored in the order that they are arranged in the marimoeditor. So if you want to rearrangeyour cells using your favorite text editor, just rearrange theorder that they're defined in the file.""",- "Text formatting is preserved": """+ "Text formatting is preserved": """marimo guarantees that however your source code wasformatted in the marimo editor is exactly how it will be stored inthe generated code. For example, whitespace, line breaks, and so on areall preserved exactly. This means that you can touch up formatting in- your text editor, either manually or using automated formatters like- Ruff, and be confident that your changes will be preserved.+ your text editor, either manually or using automated formatters like+ Black, and be confident that your changes will be preserved.""",- "Cell functions can have names": """- If you want to, you can replace the default names for cell functions+ "Cell functions can have names": """+ If you want to, you can replace the default names for cell functionswith meaningful ones.For example, change```python3@app.cell- def __(text):+ def _(text):print(text.value)return```- to+ to```python3@app.cell@@ -221,38 +213,253 @@ def __():This can make the generated code more readable.""",- "No magical tokens": """+ "No magical tokens": """marimo's generated code is pure Python; no magical syntax.""",- "Helpful error messages": """+ "Cell signatures automatically maintained": """If when editing a cell, you forget to include all a cell's refs in its- argument list, or all its defs in its returns, marimo will raise a- helpful error message the next time you try to open it in the marimo- editor. So don't worry that you'll botch a cell's signature when editing- it.+ argument list, or all its defs in its returns, marimo will fix them he next+ time you try to open it in the marimo editor. So don't worry that you'll+ botch a cell's signature when editing it.""",- "The `app` object": """- At the top of the generated code, a variable named `app` is created.- This object collects the cells into a dataflow graph, using the `cell`- decorator.+ "The `app` object": """+ At the top of the generated code, a variable named `app` is created.+ This object collects the cells into a dataflow graph, using the `cell`+ decorator.""",- "Runnable as a script": """+ "Runnable as a script": """You can run marimo apps as scripts at the command line,using Python. This will execute the cells in a- topologically sorted order, just as they would run if you opened the app+ topologically sorted order, just as they would run if you opened the appwith `marimo edit`.- For example: running our example as a script would print `Hello+ For example: running our example as a script would print `HelloWorld!` to the console.""",- }- return properties,+ """Usable as a module""": """+ Import top-level functions and classes from the notebook into other+ Python files.+ """,+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ## Importing functions and classes from notebooks++ The details of marimo's file format are important if you want to import+ functions and classes defined in your notebook into other Python modules. If you+ don't intend to do so, you can skip this section.+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ### Declaring imports used by functions and classes++ marimo can serialize functions and classes into the top-level of a file, so you can import them with regular Python syntax:++ ```python+ from my_notebook import my_function+ ```++ In particular, if a cell defines just a single function or class, and if that function or class is pure+ save for references to variables defined in a special **setup cell**, it will be serialized top-level.++ **Setup cell.** Notebooks can optionally include a setup cell that imports modules,+ written in the file as:++ <!-- note this setup cell is hardcoded in the playground example -->+ ```python+ with app.setup:+ import marimo as mo+ import dataclasses+ ```++ Modules imported in a setup cell can be used in "top-level" functions or+ classes. You can add the setup cell from the general menu of the editor under:+ ::lucide:diamond-plus:: Add setup cell.+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ### Functions and classes++ Notebook files expose functions and classes that depend only on variables defined in the setup cell (or on other such functions or classes). For example, the following cell:+ """+ )+ return+++def roll_die():+ """+ A reusable function.++ Notice the indicator in the bottom right of the cell.+ """+ return random.randint(1, 7)++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ... is saved in the notebook file as++ ```python+ @app.function+ def roll_die():+ '''+ A reusable function.++ Notice the indicator in the bottom right of the cell.+ '''+ return random.randint(1, 7)+ ```+++ Making it importable as++ ```python+ from my_notebook import roll_die+ ```+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""Standalone classes are also exposed:""")+ return++[email protected]_definition+class SimulationExample:+ n_rolls: int++ def simulate(self) -> list[int]:+ return [roll_die() for _ in range(self.n_rolls)]++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ This class is saved in the file as++ ```python+ @app.class_definition+ @dataclasses.dataclass+ class SimulationExample:+ n_rolls: int++ def simulate(self) -> list[int]:+ return [roll_die() for _ in range(self.n_rolls)]+ ```+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ /// attention | Heads up+ ///++ Not all standalone functions will be exposed in the module. If your+ function depends on variables that are defined in other cells, then it won't+ be exposed top-level.+++ For example, this function will not be exposed:+ """+ )+ return@app.cell-def __():- import marimo as mo- return mo,+def _():+ variable = 123+ return (variable,)+++def wrapped_function_example(variable):+ def not_a_top_level_function():+ """+ This function depends on a variable declared in another cell.++ As a result this function isn't exposed in the file — and the tooltip in the+ bottom-right corner indicates this.+ """+ return variable+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ## FAQ++ ### I want to edit notebooks in a different editor, what do I need to know?++ See the docs on [using your own editor](https://docs.marimo.io/guides/editor_features/watching/).++ ### I want to import functions from a marimo notebook, what do I need to know?++ See the docs on [reusable functions and+ classes](https://links.marimo.app/reusable-functions).++ ### I want to run pytest on marimo notebooks, what do I need to know?++ See the docs on [testing](https://docs.marimo.io/guides/testing/).+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ ## This notebook's source code++ The source code of this notebook is shown below:+ """+ )+ return+++def _(__file__):+ with open(__file__, "r", encoding="utf-8") as f:+ contents = f.read()+ return (contents,)+++def _(contents, mo):+ mo.ui.code_editor(contents)+ returnif __name__ == "__main__":diff --git a/mkdocs.yml b/mkdocs.ymlindex a57fa8f96b..22cdbfd422 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -114,6 +114,7 @@ nav:- Using your own editor: guides/editor_features/watching.md- Run notebooks as apps: guides/apps.md- Run notebooks as scripts: guides/scripts.md+ - Reuse functions and classes: guides/reusing_functions.md- Test notebooks:- Testing notebooks: guides/testing/index.md- pytest: guides/testing/pytest.md