Every Streamlit design decision, from caching to session state, follows from this one rule.
A Streamlit app is an ordinary Python file. Start it with:
pip install streamlit
streamlit run app.pyStreamlit starts a local web server (by default on http://localhost:8501) and opens the browser. Calls such as st.title, st.write and st.slider add elements to the page in the order they run.
The central idea is the rerun model: whenever a user changes a widget (moves a slider, clicks a button, types text), Streamlit runs your entire script again from the top. This time, the widget call returns the new value, so the code below it computes and displays updated results. There are no callbacks or event handlers required for the basic case: you write straight-line code and Streamlit handles the rest.
Consequences to keep in mind:
- Ordinary variables are reset on every rerun; anything you need to remember goes in
st.session_state. - Slow work (loading a big file, calling an API, training a model) would repeat on every click, so you cache it with
@st.cache_dataor@st.cache_resource. - Each browser tab is a separate session with its own reruns and state.
While developing, saving the file makes the app offer to rerun ("Always rerun" reruns automatically on every save), giving a fast edit-and-see loop. streamlit hello runs a built-in demo to check your installation.
Example
# app.py -> start with: streamlit run app.py
import time
import streamlit as st
st.title("Rerun demo")
n = st.slider("How many squares?", 1, 10, 3) # returns the current value
st.write("Script ran at", time.strftime("%H:%M:%S"))
st.write("Squares:", [i * i for i in range(n)])
clicks = 0 # plain variables reset on every rerun...
if st.button("Click me"):
clicks += 1
st.write("clicks =", clicks) # ...so this never goes above 1
# Moving the slider reruns the whole script: the time and n both change.Remember
streamlit run app.pyserves the script as a web app- Every widget interaction reruns the whole script top to bottom
- Plain variables reset each rerun; use session state and caching for memory and speed
Watch out for
- Expecting a normal variable to keep its value between interactions.