Not re-executing certain parts of code?

Hi!
I am new using Streamlit so maybe my question is obvious, but I am designing an app that firsts loads a bunch of data from a file (what lasts a lot of time) and then I apply my functionality. The code would be something similar as below:

array_elements = load_function()

text = st.text_input("Enter text")
option = st.selectbox("Select option", ["A", "B", "C"])

if st.button("Calculate"):
    do_things(text, option, array_elements)

The main problem I am facing is that every time a change is made on text_input and selectbox, the page reloads and executes again load_function, which takes a long time.

Is there a posibility for not executing again just that part of code, just doing it the first time the app is opened?

I answer myself as I have just came up with the solution as I have written the post.

I have used the st.session_state:

if "load" not in st.session_state:
    array_elements = load_function()
    st.session_state["load"] = array_elements

text = st.text_input("Enter text")
option = st.selectbox("Select option", ["A", "B", "C"])

if st.button("Calculate"):
    do_things(text, option, array_elements)
1 Like

Hi @Manusua , thanks for posting and great job finding your own solution :slight_smile:

I’m just going to put this here as a reference as it may be useful:
we have a st.cache which should be basically the exact thing you’re looking for.

3 Likes

To add to @willhuang’s response, we have two new cache primitives st.experimental_memo and st.experimental_singleton.

They’re conceptually simpler and much, much faster. In some of our internal tests on caching large dataframes, @st.experimental_memo has outperformed @st.cache by an order of magnitude. That’s over 10X faster! :rocket:

2 Likes