Reuse functions and classes - marimo (original) (raw)

Importing functions and classes defined in 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 reusable, testable, and easier to edit in text editors of your choice.

Prefer learning by video? Watch our tutorial on YouTube.

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 thesetup cell, or to other top-level symbols.

Example

In another script or notebook

[](#%5F%5Fcodelineno-1-1)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 thecriteria 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.

3. Import into other Python files

Now you can import your function in other notebooks or Python scripts:

[](#%5F%5Fcodelineno-4-1)# In another_script.py [](#%5F%5Fcodelineno-4-2)from my_notebook import calculate_statistics [](#%5F%5Fcodelineno-4-3) [](#%5F%5Fcodelineno-4-4)data = [1, 2, 3, 4, 5] [](#%5F%5Fcodelineno-4-5)stats = calculate_statistics(data) [](#%5F%5Fcodelineno-4-6)print(stats)

Best practices

Tip

Top-level symbols can reference other top-level symbols.

Limitations

Learn more

For more on marimo's file format, check out our documentation on using your own editor or view our file format tutorial.