Multipage App with session_state - Reload on pages sets st.session_state variables to NA

I have a multipage app, which is working ok, if I reload (F5) the app on the main page. But it does not reload the variables from st.session_state, if reloaded on another page (e.g. page1, page2). This behavior is of course not what a user wants. Therefore, the question: How to reload the entire app, if a user reloades on one of the other pages?

An example App:

.
├── home.py
└── pages
    └── page1.py

home.py

import streamlit as st

"# Home"

if "basename" not in st.session_state:
    st.session_state.basename = "a"

if "ext" not in st.session_state:
    st.session_state.ext = "txt"

if "file_name" not in st.session_state:
    st.session_state.file_name = ""

"#### Session state"
st.json(dict(sorted(st.session_state.items())))

page1.py

import streamlit as st

"#### Session state"
st.json(dict(sorted(st.session_state.items())))

"# Page1"

def get_file_name(basename, ext):
    return f"{basename}.{ext}"

if "basename" in st.session_state:
    basename = st.session_state.basename
else:
    basename = "NA"

basename = st.text_input("Basename", value=basename)
st.session_state.basename = basename

if "ext" in st.session_state:
    ext = st.session_state.ext
else:
    ext = "NA"

ext = st.text_input("Ext", value=ext)
st.session_state.ext = ext

st.session_state.file_name = get_file_name(st.session_state.basename, st.session_state.ext)

"#### Session state"
st.json(dict(sorted(st.session_state.items())))

Whenever you define a session variable in the main page and this variable is used in other pages and user reloads a page that is not a main page, apply a switch_page()

Example:

page1.py

# page is reloaded
if "basename" not in st.session_state:
    st.switch_page('home.py')  # assuming basename is first defined in home.py

By switching to the main page, the original behavior of streamlit run is simulated that is streamlit starts at main page.

Thank you very much for your reply. I think, this is a viable workaround. I didn’t know about st.switch_page(), but hoped for this kind of fix.

I added this to page1.py and it does the job:

for v in ["basename", "ext", "file_name"]:
    if v not in st.session_state:
        st.switch_page('home.py')