Streamlit Session State
Each time your app runs, the variables are all initialzed again, since the script runs from top to bottom each time a change occurs (refreshing the page, widget value changes, etc). Should you wish to have certain variables unchanged in between runs, then use the st.session_state() method.
The following code helps illustrate the difference between saving state and not doing so.
delta = None step = 0.5
humidity = 75.0
raise_humidity = st.button(“Raise humidity”) if raise_humidity: humidity += step st.metric("The humidity is: ", humidity, delta)
if “temperature” not in st.session_state: st.session_state[“temperature”] = 25.0
raise_temperature = st.button(“Raise temperature”) if raise_temperature: st.session_state[“temperature”] += step delta = step lower_temperature = st.button(“Lower temperature”) if lower_temperature: st.session_state[“temperature”] -= step delta = -step
st.metric("The temperature is: ", st.session_state[“temperature”], delta)
When you click the button to raise humidity, past the first increment, nothing more happens, and the value remains at 75.5. But for temperature, each button press, up or down, results in the value changing. You also notice that when you press the temperature buttons, the value of humidity is reset to 75, again because each run of the app means the script is executed from top to bottom.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy