Reading default index of radio button from a local file leads to weird behavior

Hello !

I’m trying to build a streamlit app with a radio button, and I want to store the value of the radio button in a local cache file. The idea is that if I shutdown my app, and restart it later, the latest value is loaded from the local cache file. I’m currently using this code:

from pathlib import Path

import streamlit as st

cache_file = Path(".streamlit_cache")
choices = ["a", "b", "c"]
index = 0
if not st.session_state.get("initialized") and cache_file.is_file():
    with cache_file.open() as f:
        selected_choice = f.read().splitlines()[0]
    print(f"loading {selected_choice} from cache")
    st.session_state["initialized"] = True
    index = choices.index(selected_choice)

choice = st.radio("choices", choices, index=index)
print(f"choice is {choice}")
with cache_file.open("w") as f:
    f.write(choice)

It almost works as I wish, but I still have one minor issue, here is how to reproduce it:

  • echo "b" > .streamlit_cache
  • streamlit run tmp.py

On the web browser, b appears selected and the logs are:

loading b from cache
choice is b

as expected.

But then, if I click on c on the web browser, a appears selected instead of c and the logs are:

choice is a

which is not the behavior I’m expected.

After that, the behavior of my app is the one I’m expecting.

Do you know how I can adapt my code to avoid this issue ?

Thanks

  1. Are you running your app locally or is it deployed?
    locally
  2. Share the full text of the error message (not a screenshot).
    no error message, see the description above
  3. Share the Streamlit and Python versions.
    $ python -V
    Python 3.10.12
    $ pip show streamlit | grep Version
    Version: 1.31.1
    
1 Like

It is actually what I would expect. When you select "c", the script is rerun. index is set to 0. st.session_state["initialized"] is True, so the body of the if is skipped. Then radio() is called with index=0, so it returns "a".

2 Likes

I don’t think so, otherwise the following snippet would always print choice is a, no matter which button you click on:

import streamlit as st

choices = ["a", "b", "c"]
index = 0

choice = st.radio("choices", choices, index=index)
print(f"choice is {choice}")

What I understand of index is that it is used to define the default value of radio, but it doesn’t override what the user actually clicks on. Otherwise, we wouldn’t be able to interact with radio when using the index argument

1 Like