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 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:
In another script or notebook
from my_notebook import my_utility_function, DataProcessor
Creating a top-level function or class¶ 1. Create a setup cell¶
First, add a setup cell to your notebook for imports that your functions or classes will need:
To add a setup cell in the editor, open the notebook menu and select "Add setup cell". (The setup cell is guaranteed to run before other cells.)
2. Define your function¶Define a single function in a cell. If the criteria 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.
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. Top-level classes are decorated with @app.class_definition
.
Now you can import your function in other notebooks or Python scripts:
# In another_script.py
from my_notebook import calculate_statistics
data = [1, 2, 3, 4, 5]
stats = calculate_statistics(data)
print(stats)
Best practices¶
Tip
Top-level symbols can reference other top-level symbols.
Limitations¶For more on marimo's file format, check out our documentation on using your own editor or view our file format tutorial.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4