Why does refreshing a subpage cause the session_state to be empty?

main.py:

import streamlit as st
if 'k' not in st.session_state:
    st.session_state['k'] = 1

st.button('refresh')

st.session_state['k'] += 1
st.write(st.session_state)

sub.py:

import streamlit as st

st.write(st.session_state)

If I navigate to localhost:8501/ and then click on the side bar to navigate to sub I get what I expect (ie see the session_state variable populated).

However if I directly navigate to /sub or I refresh the sub page then the session_state variable is cleared until I navigate to main through the side bar and back to sub.

This probably is due to some version of:
run sub.py (session_state not yet populated)
run main.py (session_state populated)
run sub.py (session_state populated and displayed)

but is there a way to run common things beforehand? Like importing from a common module or smth similar? my general goal is to have a cache_resource on the initialisation of the session_state to purposely allow mutations.

This starts a new session so everything session-scoped is lost.

Many ways, but all of them will require some duplication. Importing a module is the more concise way, AFAIK. On the other hand, there are reasons why you may want to minimize the code run for module initialization and its visible side effects. Pick your poison.

1 Like

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