Unexpected session_state behaviour

I’m not sure if this is a bug or if I’m doing something wrong so I wanted to post here before raising an issue…

import streamlit as st

if 'text' not in st.session_state:
    st.session_state.text = 'text 1'
    st.session_state.number = 42

st.session_state.text = st.text_input('text', value=st.session_state.text)
st.session_state.number = st.number_input('number', value=st.session_state.number)

st.write(st.session_state.text)
st.write(st.session_state.number)

Steps to reproduce:

  1. Update the text - the two st.write calls at the bottom show the updated text & the original number as expected
  2. Update the number - the two st.write calls at the bottom show the update text & the updated number as expected
  3. Put the text back to its original value text 1 - the two st.write calls at the bottom show the original text & the updated number as expected
  4. Put the number back to its original value 42 - the two st.write calls at the bottom now show the updated text value (even though we just put it back to its original value in step 3)

Can anybody see if this is a bug in the session_state or something wrong in my code?

Here’s an animation if it helps show the behaviour I’m seeing…

Animation

Thanks.

I had a similar issue, see here Callbacks - how to get current control value? - Using Streamlit - Streamlit
Setting the value by the value argument to number_input etc via session_state does not work.Rather define a key for the widget and set the intial value with some constant. If you use the key parameter, an entry for the widget is automatically created in the session_state dict. If you need to modify the value after the user has entered something, use a callback.
I gues one problem in general is that while the streamlit code looks like normal python, the actual operation is determined by the streamlit engine and can be quite different to what the user expects.

1 Like

Ah - thanks. That works.

I did try using the on_change callback but I couldn’t work out how to get the current value of the control into the callback. Thanks for the explanation.