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.set_page_config(layout="wide")
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):
        st.table(df.iloc[grade:(grade+1)])

display_grades()

# 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'])
    st.write(st.session_state.name0)
    #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)

    df2

    st.header("Complete")

The following error occurs when attempting to click submit_button:


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

Traceback:

File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\script_runner.py", line 350, in _run_script
    exec(code, module.__dict__)File "C:\Users\danie\Desktop\Python\Streamlit\Experiment_3_8_2.py", line 43, in <module>
    st.write(st.session_state.name0)File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\state\session_state.py", line 549, in __getattr__
    return state.__getattr__(key)File "c:\users\danie\appdata\local\programs\python\python39\lib\site-packages\streamlit\state\session_state.py", 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!
Marisa