Session State: initialization errors

I’m developing a Streamlit app for recording feedback for student assignments. Displayed on the app’s main page are rows from a csv displaying each student’s grades and info. On the sidebar are text input boxes for providing comments. The goal for the app is to write the contents of the text input boxes into a new csv column, final_comment. I’m attempting to use a session state for the sidebar. However, I’m running to persistent errors with initializing the session state.

Here’s what the app design:

Here’s my working code:

import streamlit as st
import pandas as pd

# Streamlit formatting
st.header("Demo - Level 3.8.2 (Prototype)")
st.header("Text Display")
st.subheader("Below are the submissions and grades for each student. You can use the grading interface to the left to make adjustments to the final grade. Be sure to match the correct grade field with the corresponding text.")
form = st.sidebar.form(key='comments')
submit_button = form.form_submit_button(label='Submit Final Comments')

df = pd.read_csv("Control2.csv", usecols=['last_name', 'feedback_number', 'word_count_score', 'composition_score', 'engagement_grade', 'total_score'])
df_name = pd.read_csv("Control2.csv", usecols=['first_name', 'last_name'])
number = len(df_name['last_name'])

# display single row from csv with values

def display_grades():
    for grade in range(number):


# display text_input boxes and student names in sidebar
for users in range(number):
    feedback_identifier = 'Final Comment: ' + df_name['first_name'][users] + " " + df_name['last_name'][users]
    feedback_salutation = df_name['first_name'][users] + ",\n\n"
    rb = form.text_area(feedback_identifier, value=feedback_salutation)

# writing data in session state
if submit_button:
    df = pd.DataFrame(columns=['data'])
    #Find out which items in the session state have name
    for item in st.session_state:
        if "name" in item:
            df = df.append({'data': st.session_state[item]}, ignore_index=True)

    df2 = pd.read_csv("Control2.csv")

    df2["final_comment"] = df

    df2.to_csv("Control2.csv", index=False)



The following error occurs when attempting to click submit_button:

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


File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\", line 350, in _run_script
    exec(code, module.__dict__)File "C:\Users\danie\Desktop\Python\Streamlit\", line 43, in <module>
    st.write(st.session_state.name0)File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\state\", line 549, in __getattr__
    return state.__getattr__(key)File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\state\", line 366, in __getattr__
    raise AttributeError(_missing_attr_error_message(key))

Any assistance on where I’m going wrong with the session state is much appreciated.

Hey @Daniel_Hutchinson,

The line that (i beleive) is giving you errors is this one:

You’re asking Streamlit to display the value associated with the session state key of name0, but based on the above code I see you not initialize state to have this key and value pair.

I would first make sure this is added to state in the following way:

 if "name0" not in st.session_state: 
# you may want an empty string, or a value you already have,
# I'm putting "initial name" as a place holder 
    st.session_state["name0"] = "initial name" 

you can print the state object to the screen with st.write(st.session_state) at any time to see what key:value pairs are currently stored within the object.

Let me know if this doesn’t solve your issue (and if not could you send a screenshot of your key:value pairs in state?)

Happy Streamlit-ing!