Text_input behavior for updating a session state value is not intuitive for my use-case

I have been following your posts in the other topic and was about to reply. I had a similar question a couple months ago and I believe what you want to achieve is the following:

import streamlit as st

state = st.session_state
if 'directory' not in state:
    state._directory = "D:/default_directory"

def change_directory():
    state._directory = state.directory

st.json(state)  # just for debugging, see what is happening here

st.text_input("Enter a directory", value=state._directory, key="directory", on_change=change_directory)
st.write(state.directory)

st.json(state)  # just for debugging, see what is happening here too

The key (no pun intended) is to initialize the widget with a value that is NOT the widgets key from session_state.
Credits go to @asehmi who came up with this when I had this question: Make a widget remember its value after it is hidden and shown again in later script runs

EDIT:
Actually the code above is only needed when you plan on hiding a widget and want it to remember its value (cf. my question). For your use-case, the following is sufficient:

import streamlit as st

state = st.session_state
DEFAULT_DIR = "D:/default_directory"

st.json(state)  # just for debugging, see what is happening here

st.text_input("Enter a directory", value=DEFAULT_DIR, key="directory")
st.write(state.directory)

st.json(state)  # just for debugging, see what is happening here too
1 Like