# st.cache_resource

Source: https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource

> **Tip**
>
> This page only contains information on the `st.cache_resource` API. For a deeper dive into caching and how to use it, check out [Caching](https://docs.streamlit.io/develop/concepts/architecture/caching).

* Function signature:

   ```python
   st.cache_resource(func, *, ttl, max_entries, show_spinner, show_time=False, validate, hash_funcs=None, on_release=None, scope="global", refresh_mode="foreground")
   ```

* Parameters:

   | name | type | default | description |
   |---|---|---|---|
   | func | callable |  | The function that creates the cached resource. Streamlit hashes the function's source code. |
   | ttl | float, timedelta, str, or None |  | The maximum age of a returned entry from the cache. This can be one of the following values:  None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1D", "1.5 days", or "1h23s". Note that number strings without units are treated by Pandas as nanoseconds. A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1).  Changes to this value will trigger a new cache to be created. |
   | max_entries | int or None | 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. Defaults to None. Changes to this value will trigger a new cache to be created. |
   | show_spinner | bool or str | True | Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. |
   | show_time | bool |  | Whether to show the elapsed time next to the spinner text. If this is False (default), no time is displayed. If this is True, elapsed time is displayed with a precision of 0.1 seconds. The time format is not configurable. |
   | validate | callable or None |  | An optional validation function for cached resources. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. validate must be a synchronous function; coroutine functions (async def) aren't supported. |
   | 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. |
   | on_release | callable or None |  | A function to call when an entry is removed from the cache. The removed item will be provided to the function as an argument. on_release must be a synchronous function; coroutine functions (async def) aren't supported. This is only useful for caches that remove entries normally. Most commonly, this is used session-scoped caches to release per-session resources. This can also be used with max_entries or ttl settings. TTL expiration only happens when expired resources are accessed. Therefore, don't rely on TTL expiration to guarantee timely cleanup. Also, expiration can happen on any script run. Ensure that on_release functions are thread-safe and don't rely on session state. The on_release function isn't guaranteed to be called when an app is shut down. |
   | scope | "global" or "session" |  | The scope for the resource cache. If this is "global" (default), the resource is cached globally. If this is "session", the resource is removed from the cache when the session disconnects. Because a session-scoped cache is cleared when a session disconnects, an unstable network connection can cause the cache to populate multiple times in a single session. If this is a problem, you might consider adjusting the server.websocketPingInterval configuration option. |
   | refresh_mode | "foreground" or "background" |  | How to refresh a cached resource once its ttl expires. This can be one of the following:  "foreground" (default): When the ttl expires, the next access runs the cached function synchronously. The app rerun waits until the new resource is ready. "background": Return the expired resource immediately and update it in the background. By default, Streamlit can keep returning the expired resource for one extra ttl; after that, the next call waits for a new resource. To change how long expired resources can be returned, use the runner.cacheBackgroundRefreshTTLMultiplier configuration option. This mode requires a ttl. If you set on_release, Streamlit calls it for the old resource after a successful update. It is not supported for coroutine functions. To upvote support for this combination, see GitHub issue #16800.   Note A function that refreshes in the background can't use session-specific features such as st.session_state. Pass any required session values as arguments instead. The function also shouldn't contain Streamlit commands that display elements. Streamlit doesn't replay these elements for cached results and shows a warning when the function creates them. |

* Function signature:

   ```python
   st.cache_resource.clear()
   ```

#### Example

In the example below, pressing the "Clear All" button will clear _all_ cache_resource caches. i.e. Clears cached global resources from all functions decorated with `@st.cache_resource`.

```python
import streamlit as st
from transformers import BertModel

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

@st.cache_resource
def get_model(model_type):
    # Create a model of the specified type.
    return BertModel.from_pretrained(model_type)

if st.button("Clear All"):
    # Clears all st.cache_resource caches:
    st.cache_resource.clear()
```

* Function signature:

   ```python
   CachedFunc.clear(*args, **kwargs)
   ```

* Parameters:

   | name | type | default | description |
   |---|---|---|---|
   | *args | Any |  | Arguments of the cached functions. |
   | **kwargs | Any |  | Keyword arguments of the cached function. |

## Using Streamlit commands in cached functions

### Static elements

Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this:

```python
from transformers import pipeline

@st.cache_resource
def load_model():
    model = pipeline("sentiment-analysis")
    st.success("Loaded NLP model from Hugging Face!")  # 👈 Show a success message
    return model
```

As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the `st.success` message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an `st.` command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators.

You can also use this functionality to cache entire parts of your UI:

```python
@st.cache_resource
def load_model():
    st.header("Data analysis")
    model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT)
    st.success("Loaded model!")
    st.write("Turning on evaluation mode...")
    model.eval()
    st.write("Here's the model:")
    return model
```
