I keep getting an initialization error, not sure if it has something to do with my IDE:
AttributeError: st.session_state has no attribute “key”. Did you forget to initialize it?
I am using Streamlit version=1.24.0, spyder=5.4.3, python=3.9.13
Below is an example:
import streamlit as st
if ‘key’ not in st.session_state:
st.session_state.key = ‘value’
The correct way to set a key in session state is by using the dictionary-style indexing as such;
st.session_state['key'] = ‘value’
Here’s the modified code from your snippet above:
import streamlit as st
if 'key' not in st.session_state:
st.session_state['key'] = 'value'
# Update session state
st.session_state['key'] = 'value4'
# Read session state
st.write(st.session_state['key'])
I see you’re running the script in the console. This might be the cause of the error you’re seeing because Session State does not function when running a script without using streamlit run <YOU-APP-NAME.py>
To fix this, please save the script in a .py file (e.g. streamlit_app.py) and then run it on the console as such;
Code for streamlit_app.py:
import streamlit as st
if 'key' not in st.session_state:
st.session_state['key'] = 'value'
# Update session state
st.session_state['key'] = 'value4'
# Read session state
st.write(st.session_state['key'])
Save it and run (make sure you’re in the same directory when running this):