KeyError when accessing Streamlit session_state in Python script despite initializing session_state variable

47 views Asked by At

I'm encountering a KeyError when trying to access Streamlit's session_state in my Python script, despite initializing the session_state variable. Here's my code:

import streamlit as st

def main():
    if "show_text" not in st.session_state.keys():
        st.session_state["show_text"] = False

    st.markdown("# My App")

    if st.button("Show text!"):
        st.session_state["show_text"] = True

    if st.session_state["show_text"] is True:
        st.markdown("Lorem ipsum...")

if __name__ == "__main__":
    main()

Upon running the script, I receive the following error message:

KeyError: 'st.session_state has no key "show_text". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'

When I open the app in the browser, it functions as intended. However, the error message is bothersome when I first run the Python script to get the command for starting the app in the browser. I'm confused because I've already initialized session_state as shown in the code. Any insights into what might be causing this error would be greatly appreciated.

I've carefully reviewed the documentation provided in the error message and attempted several solutions, but unfortunately, none have resolved the issue. I ensured that I initialized the session_state variable as suggested, but the KeyError persists. Any further guidance or alternative solutions would be greatly appreciated. Thank you for your help!


UPDATE:

If I start the following example in the terminal, I don't receive an error message. I'm wondering why this error message occurs in the first example and not in this one.

import streamlit as st


def main():

    if "show_text" not in st.session_state.keys():
        st.session_state["show_text"] = False

    st.markdown("# My App")

    if st.button("Show text!"):
        st.write(st.session_state["show_text"])


if __name__ == "__main__":
    main()
1

There are 1 answers

1
matleg On

At the top of the error stack, there is surely a warning that explains why it works when you start it with streamlit run your_script.py and not with python your_script.py:

WARNING streamlit.runtime.state.session_state_proxy: Session state does not function when running a script without `streamlit run`

There you have the answer.