I would like to understand why streamlit removes keys from st.session_state
, once the widgets with the assigned keys are not rendered.
import streamlit as st
st.info(st.session_state)
if "another" not in st.session_state and "another_state" in st.session_state:
st.session_state["another"] = st.session_state["another_state"]
st.info(st.session_state)
if st.checkbox("main", value=True):
st.session_state["another_state"] = st.checkbox("another", key="another")
st.info(st.session_state)
When the “main” checkbox is unchecked, the script is re-runs and the “another” checkbox is not rendered at all. But in that time the “another” key is present in st.session_state
.
Then, after checking the “main” checkbox again, the “another” key is not present in the st.session_state
anymore and thus the checkbox cannot read it and it doesn’t restore it’s state.
To achieve the another checkbox state persistency I had to add an extra key “another_state” which is not bound to the checkbox widget and which remains present in the st.session_state
across all re-runs and thus can be used to initialize the another checkbox in case that its key is lost.
The question is, why is the key “another” removed from the st.session_state at all?
Thank you very much!