Why do default values cause a session state warning?

@betaigeuze The recommended solution is to not set a value in the widget if you’re also setting it with session state. If you have a situation where you’re not sure if the value has been set in session state, and you want to specify a default value in case it hasn’t, you can do something like this:

import streamlit as st

if st.checkbox("Set default value"):
    st.session_state["number_input"] = 5.0


# If the session state has a value for "number_input", use that value, and *don't* set a default value.
if "number_input" in st.session_state:
    st.number_input("Number input", key="number_input")
# Otherwise, set a default value.
else:
    st.number_input("Number input", key="number_input", value=5.0)
3 Likes