Control flow¶
Controlling when cells run¶
- Use
mo.stop
to halt execution of a cell when a condition is met. - Combine
mo.stop
withmo.ui.run_button
to gate execution on button click. - Use
mo.ui.refresh
to make cells run periodically.
Lazy execution
In addition to these utilities, you can configure the runtime to be lazy, marking cells as stale instead of automatically running them.
marimo.stop
¶
Stops execution of a cell when predicate
is True
When predicate
is True
, this function raises a MarimoStopError
. If
uncaught, this exception stops execution of the current cell and makes
output
its output. Any descendants of this cell that were previously
scheduled to run will not be run, and their defs will be removed from
program memory.
Examples:
PARAMETER | DESCRIPTION |
---|---|
predicate
|
The predicate indicating whether to stop.
TYPE:
|
output
|
The output to be assigned to the current cell.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
MarimoStopError
|
When |
Threading¶
marimo.Thread
¶
Bases: Thread
A Thread subclass that can communicate with the frontend.
mo.Thread
has the same API as threading.Thread,
but mo.Thread
s are able to communicate with the marimo
frontend, whereas threading.Thread
can't.
Threads can append to a cell's output using mo.output.append
, or to the
console output area using print
. The corresponding outputs will be
forwarded to the frontend.
Writing directly to sys.stdout or sys.stderr, or to file descriptors 1 and 2, is not yet supported.
Thread lifecycle. When the cell that spawned this thread is invalidated
(re-run, deleted, interrupted, or otherwise errored), this thread's
should_exit
property will evaluate to True
, at which point it
is the developer's responsibility to clean up their thread.
Example.
def target():
import time
import marimo as mo
thread = mo.current_thread()
while not thread.should_exit:
time.sleep(1)
print("hello")
should_exit
property
¶
Whether this thread should exit.
Returns True
when the cell that spawned this thread has been invalidated;
for example, if the cell:
- was re-run
- was deleted
- was interrupted
then this property evaluates to True.
It is the developer's responsibility to clean up and finish their
thread when this flag is set. Retrieve the current mo.Thread
with