st.cache

When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called it should check three things:

  1. The name of the function
  2. The actual code that makes up the body of the function
  3. The input parameters that you called the function with

If this is the first time Streamlit has seen those three items, with those exact values, and in that exact combination, it runs the function and stores the result in a local cache.

Then, next time the function is called, if those three values have not changed Streamlit knows it can skip executing the function altogether. Instead, it just reads the output from the local cache and passes it on to the caller.

The main limitation is that Streamlit’s cache feature doesn’t know about changes that take place outside the body of the annotated function.

For more information about the Streamlit cache, its configuration parameters, and its limitations, see Caching.

Function decorator to memoize function executions.
Function signature

st.cache(func=None, persist=False, allow_output_mutation=False, show_spinner=True, suppress_st_warning=False, hash_funcs=None, max_entries=None, ttl=None)

Parameters

func (callable)

The function to cache. Streamlit hashes the function and dependent code.

persist (boolean)

Whether to persist the cache on disk.

allow_output_mutation (boolean)

Streamlit normally shows a warning when return values are mutated, as that can have unintended consequences. This is done by hashing the return value internally.

If you know what you're doing and would like to override this warning, set this to True.

show_spinner (boolean)

Enable the spinner. Default is True to show a spinner when there is a cache miss.

suppress_st_warning (boolean)

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

hash_funcs (dict or None)

Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used.

max_entries (int or None)

The maximum number of entries to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None.

ttl (float or None)

The maximum number of seconds to keep an entry in the cache, or None if cache entries should not expire. The default is None.

Was this page helpful?

forum

Still have questions?

Our forums are full of helpful information and Streamlit experts.