priority_high

Important

This is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here.

Function decorator to store singleton objects.

Each singleton object is shared across all users connected to the app. Singleton objects must be thread-safe, because they can be accessed from multiple threads concurrently.

(If thread-safety is an issue, consider using st.session_state to store per-session singleton objects instead.)

You can clear a memoized function's cache with f.clear().

Function signature

st.experimental_singleton(func=None, *, show_spinner=True, suppress_st_warning=False)

Parameters

func (callable)

The function that creates the singleton. Streamlit hashes the function's source code.

show_spinner (boolean)

Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the singleton is being created.

suppress_st_warning (boolean)

Suppress warnings about calling Streamlit functions from within the singleton function.

Example

@st.experimental_singleton
def get_database_session(url):
    # Create a database session object that points to the URL.
    return session

s1 = get_database_session(SESSION_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(SESSION_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the connection object in s1 is the same as in s2.

s3 = get_database_session(SESSION_URL_2)
# This is a different URL, so the function executes.

By default, all parameters to a singleton function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable:

@st.experimental_singleton
def get_database_session(_sessionmaker, url):
    # Create a database connection object that points to the URL.
    return connection

s1 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value - even though the _sessionmaker parameter was different
# in both calls.

A singleton function's cache can be procedurally cleared:

@st.experimental_singleton
def get_database_session(_sessionmaker, url):
    # Create a database connection object that points to the URL.
    return connection

get_database_session.clear()
# Clear all cached entries for this function.

Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached.

In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached.

import numpy as np
import pandas as pd
import streamlit as st
from transformers import AutoModel

@st.experimental_singleton
def get_model(model_type):
    # Contains a static element st.bar_chart
    st.bar_chart(
        np.random.rand(10, 1)
    )  # This will be recorded and displayed even when the function is skipped

    # Create a model of the specified type
    return AutoModel.from_pretrained(model_type)

bert_model = get_model("distilbert-base-uncased")
st.help(bert_model) # Display the model's docstring

Supported static st elements in cache-decorated functions include:

  • st.alert
  • st.altair_chart
  • st.area_chart
  • st.bar_chart
  • st.ballons
  • st.bokeh_chart
  • st.caption
  • st.code
  • st.components.v1.html
  • st.components.v1.iframe
  • st.container
  • st.dataframe
  • st.echo
  • st.empty
  • st.error
  • st.exception
  • st.expander
  • st.experimental_get_query_params
  • st.experimental_set_query_params
  • st.graphviz_chart
  • st.help
  • st.info
  • st.json
  • st.latex
  • st.line_chart
  • st.markdown
  • st.metric
  • st.plotly_chart
  • st.progress
  • st.pydeck_chart
  • st.snow
  • st.spinner
  • st.success
  • st.table
  • st.text
  • st.vega_lite_chart
  • st.warning

All other st commands, including widgets, forms, and media elements are not supported in cache-decorated functions. If you use them, the code will only be called when we detect a cache "miss", which can lead to unexpected results. Which is why Streamlit will throw a CachedStFunctionWarning, like the one below:

import numpy as np
import pandas as pd
import streamlit as st
from transformers import AutoModel

@st.experimental_singleton
def get_model(model_type):
    # Contains an unsupported st command
    st.slider("Select a value", 0, 10, 5) # Streamlit will throw a CachedStFunctionWarning

    # Create a model of the specified type
    return AutoModel.from_pretrained(model_type)

bert_model = get_model("distilbert-base-uncased")
st.help(bert_model) # Display the model's docstring

Was this page helpful?

editSuggest edits
forum

Still have questions?

Our forums are full of helpful information and Streamlit experts.