Another session_state question

Summary

To make code easier to read, I store st.session_state in a variable (eg. ss = st.session_state), and I do this in main.py and modules I import. Recently, I stumbled upon this thread about module state and started to wonder if using “ss = st.session_state” could create concurrency issues (ie. sharing module state between users).

For example, I tested the below in 2 separate tabs in a browser:

Steps to reproduce

Code snippet:

#Module debug2.py
import streamlit as st
ss = st.session_state

def fake():
    ss.button = True

#Module debug.py
import streamlit as st
import debug2

ss = st.session_state
st.write(ss) #Should be empty on first run, then contain 'button' == True in subsequent runs

if 'button' not in ss:
    ss.button = False

st.button('Push', on_click=debug2.fake)

st.write(ss) #Should contain 'button' == True

Expected behavior:

If concurrency was happening, I should see ‘button’ == True in a freshly opened tab, but it’s not the case, it always opens as empty, ie. {}. It’s good, I don’t want to share state between users, but I don’t understand what’s happening here.

I even tried the code exactly as in the referenced thread but replaced dict() by session_state, and could not see concurrency.

My questions:

  1. Can someone explain the difference between the above the thread I shared in the description?
  2. Is storing st.session_state in a variable a bad practice? Should I always use “st.session_state” instead?

Thank you (Streamlit is awesome by the way :slight_smile: )

  1. Can someone explain the difference between the above the thread I shared in the description?

I cannot answer exactly but I suspect this has to do with session_state being managed per-session somewhere in the Streamlit internals. The ‘real’ session state does not store the value of the a key in a dictionary like session_state['a'], but a copy of session_state for each unique session_id identifiers. The getter and setter methods for the session_state that you see make sure that when you assign ss.button = True, it only happens for the current session.

If you want the alias, I would simply from streamlit import session_state as ss.

2 Likes

Thank you @ennui, I love the suggested solution, clean and simple.

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