AttributeError: st.session_state has no attribute "key". Did you forget to initialize it?

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’

Update session state

st.session_state.key = ‘value4’

Read session state

st.write(st.session_state.key)

1 Like

Hi @emad_mohiyeddini,

Thanks for posting!

The error is coming from this line

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'])
1 Like

Hi @tonykip thanks for your reply; I also tried that, but still get the same error - please see below screenshot

@blop did you find a solution to this problem? I can see you had similar issue.

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):

streamlit run streamlit_app.py

great thanks for helo here.I understand the problem now

1 Like

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