St.session_state not getting updated briefly (at random times)

Summary

Below I have attached a code, which should disable the text input for 5 seconds after a value is entered. While running this code. Its working most of the time. But in the middle I am briefly getting an error. I felt, that st.session_state is not getting updated some times. Want to understand if there is any work around, or if I am using any functions in a wrong way.

Steps to reproduce

Code snippet:

import time
import streamlit as st


def disable():
    st.session_state["disabled"] = True


def enable():
    st.session_state["disabled"] = False


print("0", st.session_state)

if "disabled" not in st.session_state:
    st.session_state["disabled"] = False
    print("1", st.session_state)

print("2", st.session_state)

print("3", st.session_state)

if user_input := st.text_input(
    "Enter some text",
    disabled=st.session_state.disabled,
    on_change=disable
):
    # Do some processing with input
    time.sleep(5)
    enable()
    st.experimental_rerun()

Play-around the UI for some-time.

Expected behavior:

Text field should get disabled for 5 seconds after every onchange event.

Actual behavior:

Though thatโ€™s happening, occasionally, I am noticing the following logs. Based on the logic st.session_state should not be empty.

0 {}
1 {}
2 {}
3 {}
2023-07-21 11:43:40.192 Uncaught app exception
Traceback (most recent call last):
  File ".venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__
    return self[key]
  File ".venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__
    return get_session_state()[key]
  File ".venv/lib/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__
    raise KeyError(key)
KeyError: 'disabled'

Debug info

  • Streamlit version: 1.24.1
  • Python version: 3.10.11
  • OS version: Ubuntu 22.04
  • Browser version: Google Chrome Version 114.0.5735.198

Additional information

I am getting this error briefly. And itโ€™s getting resolved automatically after some time. But when I am trying to use this type of logic in a larger application, its running into some complex errors

1 Like

Hi @eldos-dl

Here are some related forum posts on why session states may not refresh (essentially when the app refreshes the session state also starts over).

The following shows how to resolve this:

Hope this helps!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.