Update session_state variables fails after submit

Hi there,
I am struggling to understand how session_state works with respect to the submit form. I have a variable that is updated when the a button is pressed. However, when later in the code I submit a form to use that value, it somehow gets back to its original value. The code is:

with st.container():
    st.header("Manual configuration")
    with st.expander("Columns geometry:"):
    col_1,col_2,col_3,col_4,col_5,col_6,col_7,col_8=st.columns(8); # divide the space into columns
    col_2_value=col_2.selectbox("C1 type",options=["S","D","W"],index=1,key="col_2_key");

with st.container():
    def update():
        st.session_state["col_2_key"] = "S";

    column_presets=st.columns(4); # Create the columnspan

The code works and if it returns “S” when the the button is clicked.

However, later on I have a “submit” button as:

    with st.form("Run analysis"):
        submitted = st.form_submit_button("Run analysis"); # create button analysis
        if submitted:

When I press the “submit” button, the value “S” charges back into “D” again. That’s not really clear to me.
Apologies it might be very obvious but could someone please:

  1. explain to me why it happens? It seems like the code re-run again from 0 instead of memorising the value
  2. Help me carry the new value forward into the analysis section?

Thanks a lot for helping.

Hi @Gabriele_Granello , you could try the following with your code:

  1. remove ; from various parts of the code - it is not required
  2. For the statement with the ’ selectbox’, delete the key parameter and change the variable name (col_2_value) to st.session_state.col_2_key, like below

st.session_state.col_2_key = col_2.selectbox(“C1 type”, options=[“S”,“D”,“W”], index=1)


Thanks a lot for helping @Shawn_Pereira. I think the bug is within the expander, and I have managed to isolate it here:

You can see the screencast too