Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท State and Caching

How Streamlit Reruns Your Script

Understand the Streamlit execution model: every widget interaction reruns the whole script. Learn what resets, what survives and why this shapes every app.

Most web frameworks react to events: a click calls a handler, the handler changes one piece of the page. Streamlit works differently, and this difference is the single most important idea in the whole framework. Every time a user interacts with a widget, Streamlit runs your script again from the first line to the last. There are no handlers, no routes and no manual page updates. The script is the page.

This model is why a Streamlit app can be ten lines long. It is also why beginners get surprised: a normal variable that you increment on a button click goes back to zero on the next click, because the script started over. In this lesson you will learn exactly what happens during a rerun, what is thrown away, what survives, and how to reason about your code once you accept that it always runs top to bottom.

Streamlit itself cannot run inside this site, because it needs a Python server that keeps a WebSocket open to your browser. The Streamlit code below is shown read-only, and every idea is demonstrated with a small, clearly labelled Python stand-in that runs in your browser. The stand-ins copy the behaviour of the model, not the library.

The execution model in one picture

flowchart LR
    A["Script runs<br/>top to bottom"] --> B["Browser shows<br/>the result"]
    B --> C["User changes<br/>a widget"]
    C --> D["Streamlit stops the old run<br/>if still running"]
    D --> A

A widget change is not an event handler call. It is a request to run the whole script again.

Three things trigger a rerun: the user changes a widget (types, clicks, moves a slider), your code calls st.rerun(), or you edit the source file and choose "Rerun" (or turn on "Always rerun"). Opening the app for the first time is simply the first run.

A counter that does not count

This is the classic first mistake. Read it and predict what happens when the button is pressed three times.

Python
import streamlit as st

count = 0
if st.button("Add one"):
    count += 1
st.write("Count:", count)

The page shows Count: 0. You press the button: the script reruns, the button now returns True for this one run, count becomes 1, and the page shows Count: 1. You press it again: the script reruns from the top, count = 0 executes first, the button returns True, and the page shows Count: 1 again. The variable never gets past one, because it is created fresh on every run.

The next TryIt reproduces this without Streamlit. A function script() plays the role of your app file. The rerun() helper plays the role of Streamlit: it calls the script from the top and tells it whether the button was clicked in this run.

Python Stand-in: a plain variable resets on every rerun

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three clicks show Count: 1. The fix is to store the number somewhere that is not recreated: that place is st.session_state, the subject of the next lesson.

What resets and what survives

Think of a rerun as starting a fresh Python run of the file, but inside a long-lived process. That gives a clear rule.

Thing Survives a rerun?
Local variables and module-level variables assigned in the script No, recreated by the code that assigns them
Imported modules (import pandas as pd) Yes in practice, Python caches imports in sys.modules
Widget values Yes, Streamlit remembers them per widget
st.session_state Yes, until the browser tab session ends
Results of @st.cache_data / @st.cache_resource functions Yes, until the cache entry expires or is cleared
Files you wrote to disk Yes, they are outside Python
Global variables defined in an imported module Yes, but shared by every user: usually a bug

The last row is a trap. A module imported once lives for the whole server process and is shared by all visitors. A list in an imported module that you append to will grow for everyone. Per-user data belongs in session state; shared, read-only data belongs in a cache.

Widgets return values, they do not call you back

A widget call is an ordinary function call that draws the widget and returns its current value. That is why code reads like a script:

Python
import streamlit as st

name = st.text_input("Your name", "Ada")
age = st.slider("Your age", 0, 100, 30)
st.write(f"{name} will be {age + 10} in ten years.")

On the first run, text_input returns the default "Ada" and slider returns 30. When the user edits the name, the browser sends the new value, Streamlit stores it, and reruns the script. This time text_input returns the new text. The last line recomputes with fresh values. You never wrote "when the name changes, update the label": the script is the update rule.

This style is called dataflow programming, and it has a pleasant consequence. Your app is always consistent with its inputs. There is no way to forget to refresh a label, because the label is recomputed from scratch.

Seeing the order of execution

Because the script runs in order, anything that depends on a widget must come after it. A widget that sits below the code using its value will lead to a NameError or stale data. Look at this stand-in, which logs each step so you can see the order and the cost of a rerun.

Python Stand-in: logging a few reruns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three interactions produced three complete runs. That is the cost model of Streamlit: work in your script costs time on every interaction. If a line loads a 200 MB file, every slider move loads it again. Caching is the cure, and it is why caching gets its own lesson.

Interrupting a run

If the user changes a widget while the script is still running, Streamlit stops the old run (it raises an internal exception at the next Streamlit call) and starts a new one. Long computations that never call Streamlit cannot be interrupted until they finish, which is another reason to keep expensive work cached or in a background worker.

Stopping and rerunning on purpose

Two functions give you control of the run itself:

  • st.stop() ends the current run at that line. Everything below does not execute. It is the clean way to say "do not continue until the user has supplied a file or logged in".
  • st.rerun() aborts the current run and starts a new one immediately. Use it when you change state and want the page to reflect it right away, for example after a form saves data.
Python
import streamlit as st

uploaded = st.file_uploader("Upload a CSV", type="csv")
if uploaded is None:
    st.info("Waiting for a file.")
    st.stop()

st.success("File received, continuing.")   # only reached after an upload

Beware of st.rerun() inside code that always runs: if the same condition is true on every run you get an endless loop. Guard it with a state change that stops being true.

Common mistakes

  • Counting with a plain variable. Use st.session_state for anything that must outlive one run.
  • Loading data at the top of the file without a cache. It reloads on every click.
  • Using a widget before it is defined. Order matters: define widgets first, then use their values.
  • Mutating a shared global. Module-level mutable objects are shared across users.
  • Expecting print to change the page. Only st.* calls draw. print goes to the server terminal.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user moves a slider in a Streamlit app. What happens?

    Streamlit reruns the entire script after every widget interaction. There are no per-widget handlers by default (callbacks are optional, and the script still reruns afterward).
  2. 2. Why does count = 0 followed by if st.button(...): count += 1 never go above 1?

    Each rerun executes count = 0 first. The value must be kept in st.session_state to survive between runs.
  3. 3. Which one survives a rerun?

    Session state is the per-user storage that persists between reruns. Plain variables are recreated by the code that assigns them.
  4. 4. What is st.stop() for?

    st.stop() halts only the current run, which is handy for waiting on required input such as an uploaded file.

Summary

  • Every widget change reruns the whole script from top to bottom; the script is the page.
  • Widgets are function calls that return the current value, so code reads in a straight line.
  • Plain variables reset on each run; session state, widget values and caches persist.
  • Expensive work in the script is repeated on every interaction unless it is cached.
  • st.stop() ends a run early, st.rerun() starts a new run immediately.
  • Module-level mutable objects are shared by all users, so keep per-user data in session state.

Next: Session State