Problem with initializing session_states in streamlit

This is my code and although I initialize the session state, I have confilict with that.


import streamlit as st

if "user_inputs" not in st.session_state:
    st.session_state["user_inputs"] = True

# Loop over the 8 questions
for i in range(8):
    # Get the question
    question = f'Question {i+1}'
    # Add it to the page
    st.subheader(question)
    
    # Create 3 checkbox options
    checkbox1 = st.checkbox('Option 1')
    checkbox2 = st.checkbox('Option 2')
    checkbox3 = st.checkbox('Option 3')
    
    # Save the checkbox inputs in the session state object
    
    st.session_state.user_inputs[f'{question}_checkbox_1'] = checkbox1
    st.session_state.user_inputs[f'{question}_checkbox_2'] = checkbox2
    st.session_state.user_inputs[f'{question}_checkbox_3'] = checkbox3
    
    # Create an integer input
    integer_input = st.number_input('Integer Input')
    
    # Save the integer input in the session state object
    st.session_state.user_inputs[f'{question}_integer_input'] = integer_input
    
# Create a slider
slider = st.slider('Slider', 0, 100)

# Save the slider value in the session state object
st.session_state.user_inputs['slider'] = slider

# Add a submit button
if st.button('Submit'):
    st.success('Form submitted!')

I tried different ways to initialize but they didn’t work. I mean when I try something like st.session_state.user_inputs = "test" or st.session_state["user_inputs"] = "test", again I have same error:

The erorr is:

st.session_state has no attribute “user_inputs”. Did you forget to
initialize it? More info:
Add statefulness to apps - Streamlit Docs

I try to create a kinds of form and I received a repetitive error.

Modify your user_inputs init value to a dictionary like below as you are actually using it as a dictionary and not a bool.

st.session_state["user_inputs"] = {}

Then add unique keys to your checkbox() and number_input().

2 Likes

Thank you :vulcan_salute:

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