Not to run entire script when a widget value is changed?

Hi,

I started using Streamlit in one of my projects and immediately fell in love with it. But I got a problem that really bothers me, so any help would be greatly appreciated.

My code flows like this:

  1. Load data from files
  2. Do some computation and results populate a list
  3. When use selects an item from the list, some relevant text would be printed out as text.

My problem is that, every time I select a new item from the list, the entire script reruns from the beginning, including data loading and computation, which is uncalled for and time consuming.

How can I make it just update the text printing part when I choose a new item from the list?

Thanks in advance!

Richard

I guess thats a good use case for @st.cache, if you have a large chunk of code that only needs to run once (as long as the parameters don’t change) then wrap it in a function and decorate that function with @st.cache.
E.g.

@st.cache
def long_running_function(p1, p2, p3):
    #your long computation here

Documentation for st.cache is here
https://streamlit.io/docs/api.html#streamlit.cache

Thank you Alexandre!

This works, just a bit awkward when a script gets a little more complex. Hope Streamlit can be more flexible.

Beside the @st.cache the key is really how you structure you script. If you could somehow save the data from the long_running_computation when it’s done and the user could click a button to go to the next step/ page then you might be home free.

You can save to a temporary file or a database. That depends on use case. Whether you save the same file all the time (if only one user) or you need to save to a unique file every time and let the user select it on the next screen is up to you.

I’ve heard there is also work in progress on being able to save the state (for example the result of the calculation) between script reruns.

At work i’m working on an application that will be structured into three steps/ pages.

  1. Run long running backtest/ simulation and save results to file(s).
  2. Let user select file(s) and validate input/ output if needed.
  3. Let user select file(s) and provide interactive analytics to end user based on simulation results.

When state is implemented I can either save the results or the paths of the files so that the user does not need to select them.