Hello there đź‘‹

Thanks for stopping by! We use cookies to help us understand how you interact with our website.

By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.

Caching and state

Optimize performance and add statefulness to your app!

Streamlit provides powerful cache primitives for data and global resources. They allow your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations.

Cache data

Function decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).

@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data

Cache resource

Function decorator to cache functions that return global resources (e.g. database connections, ML models).

@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" )

Streamlit re-executes your script with each user interaction. Widgets have built-in statefulness between reruns, but Session State lets you do more!

Context

st.context provides a read-only interface to access cookies and headers.

st.context.cookies st.context.headers

Session State

Save data between reruns and across pages.

st.session_state["foo"] = "bar"

Query parameters

Get, set, or clear the query parameters that are shown in the browser's URL bar.

st.query_params[key] = value st.query_params.clear()
delete

Get query parameters

Get query parameters that are shown in the browser's URL bar.

param_dict = st.experimental_get_query_params()
delete

Set query parameters

Set query parameters that are shown in the browser's URL bar.

st.experimental_set_query_params( {"show_all"=True, "selected"=["asia", "america"]} )
forum

Still have questions?

Our forums are full of helpful information and Streamlit experts.