Does streamlit re-load python file from beginning upon clicking checkbox?

Hi, I am currently using streamlit to get realtime data from somewhere else, built the DataFrame, and draw it on screen. Works perfectly.

However, when I add checkbox as written below, I noticed on console that “start” is being called times everytime I click the checkbox and df contents are being reset to initial empty state.

  1. Is this expected behavior?
  2. Is there any way to keep df content without external files?
import asyncio
import streamlit as st
import pandas as pd
df = pd.DataFrame(columns=[..., 'TL', ...]) # at this point empty df
cb = st.sidebar.checkbox("cb title")

async def main(placeholder:st._DeltaGenerator):
  global df
  print("start")
    while True:
      # do real time stuff and build df
      visualize_df = df[df['TL']==cb] if cb else df # visualize_df is going to have unfiltered if unchecked
      with placeholder.container():
        st.dataframe(vizualize_df)
try:
  placeholder = st.empty()
  asyncio.run(main(placeholder))
except KeyboardInterrupt:
  pass

Hi @ghints,

Thanks for posting!

Check out our docs on the Streamlit execution model.

Streamlit’s architecture allows you to write apps the same way you write plain Python scripts. To unlock this, Streamlit apps have a unique data flow: any time something must be updated on the screen, Streamlit reruns your entire Python script from top to bottom.

This can happen in two situations:

  • Whenever you modify your app’s source code.
  • Whenever a user interacts with widgets in the app. For example, when dragging a slider, entering text in an input box, or clicking a button.

Whenever a callback is passed to a widget via the on_change (or on_click) parameter, the callback will always run before the rest of your script. For details on the Callbacks API, please refer to our Session State API Reference Guide.

In other words, yes, this is expected behavior.

Can you clarify what you mean by keeping df content without external files? Are you looking to write the data to a database?

Caroline :balloon:

Hi @Caroline,
thank you very much for your prompt reply.

  1. Glad it is expected behavior.
  2. I was hoping that there would be some immutable variable or some other mechanism from streamline library that I can use to store data without using database or file even under the condition of redraw / restart.
  3. Is localstorage an option?

Hi @ghints,

If you’re running the app locally, you could write data to a local file. Otherwise, I would recommend using some type of database or a Google Sheet.

Caroline

1 Like