St.session-state has too much dependencies as a data class

Although session-state was designed like a dictionary, its behavior is not totally identical to a dictionary.

You want to implement functionalities separately from the frontend, and you only use the st.session-state from st in your backend to share the data.

Your backend is totally independent from the streamlit frontend, and you can write the unittests for the functionalities. Unfortunately, it won’t work because of some logic behind st.session-state.

This can be solved by having

### shared.py
db = {}

In every script, you can use db instead of st.session-state,

from shared import db

db["key"] = "some data"

then, db will mimic the st.session-state experience, and it won’t cause an error in your isolated unittests.
It is not a proper solution. I believe this issue must be handled by improving the st.session-state module.

No, it won’t. Your db will be app-scoped, not session-scoped.

To me at least it is not clear what improvements you are suggesting.

Let me start with a simple example.

import unittest
import streamlit as st


def delete():
    if len(st.session_state["messages"]) == 1:
        return
    st.session_state["messages"] = st.session_state["messages"][:-1]


class TestDeleteFunction(unittest.TestCase):
    def test_delete_with_multiple_messages(self):

        st.session_state['messages'] = [
            {'role': 'user', 'content': 'Message 1'},
            {'role': 'assistant', 'content': 'Response 1'},
            {'role': 'user', 'content': 'Message 2'}
        ]

        delete()

        self.assertEqual(len(st.session_state['messages']), 2)
        self.assertEqual(st.session_state['messages'], [
            {'role': 'user', 'content': 'Message 1'},
            {'role': 'assistant', 'content': 'Response 1'}
        ])


if __name__ == '__main__':
    unittest.main()

The unittest will cause an error.

KeyError: 'st.session_state has no key "messages". Did you forget to initialize it?

When I mentioned ‘mimic’, I just mentioned it as a dictionary shared globally. I might be not true because I don’t know about session-state perfect.

The point is that, if we use st.session-state as a data holder when we develop backend,
it causes an error during unittest. It is possible that I develop all backend with the shared.db, and then, in app.py, I always update st.session-state using shared.db.
However, if I were you, who already know very well how st.session-state work, I would touch st.session-state a bit to enhance the extensibility.

Or not. I am not sure if it is a reasonable approach because I didn’t look up the source code of st.session-state.

Ok, I see. So st.session_state doesn’t work in code like this because it needs an actual streamlit application running. I am not familiar with the code either, but I guess there are good reasons for that. I don’t think it would be productive discussing them here and I might be totally wrong anyway, so let’s just accept that it is how it is and it isn’t going to change anyime soon.

Now, looking at your SUT, it seems to me like a bit or domain logic that doesn’t need to depend on streamlit and just got that dependency by chance. You don’t need anything streamlit to manipulate a list of messages. So this is what I would do.

import unittest
import streamlit as st


def delete(messages):
    if len(messages) > 1:
        del messages[-1]


class TestDeleteFunction(unittest.TestCase):
    def test_delete_with_multiple_messages(self):
        messages = [
            {"role": "user", "content": "Message 1"},
            {"role": "assistant", "content": "Response 1"},
            {"role": "user", "content": "Message 2"},
        ]

        delete(messages)

        self.assertEqual(
            messages,
            [
                {"role": "user", "content": "Message 1"},
                {"role": "assistant", "content": "Response 1"},
            ],
        )

Then in your production code you would call delete(st.session_state["messages"])

To test anything that really has to depend on streamlit, I am afraid you will need to use AppTest.

In that case, I would try to make any backend more independent on streamlit.
It would be actually better practice, because adding frontend dependency to backend is already a bad signal.

Thank you for your replies.