# st.cache_data

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

> **Tip**
>
> This page only contains information on the `st.cache_data` API. For a deeper dive into caching and how to use it, check out [Caching](https://docs.streamlit.io/develop/concepts/architecture/caching). To keep dashboards fast with `refresh_mode="background"`, see [Build advanced dashboards](https://docs.streamlit.io/develop/concepts/design/dashboards).

* Function signature:

   ```python
   st.cache_data(func=None, *, ttl, max_entries, max_size, show_spinner, show_time=False, persist, hash_funcs=None, scope="global", refresh_mode="foreground")
   ```

* Parameters:

   | name | type | default | description |
   |---|---|---|---|
   | func | callable |  | The function to cache. Streamlit hashes the function's source code. |
   | ttl | float, timedelta, str, or None |  | The maximum time to keep an entry in the cache. Can be one of:  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". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1).  Note that ttl will be ignored if persist="disk" or persist=True. |
   | 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. |
   | max_size | int, str, or None |  | The maximum serialized (pickled) size of this function's in-memory cache. An integer is a number of bytes. A string must include a unit, such as "500MB" or "1.5GiB". Units are case-insensitive. The KB / MB / GB / TB and KiB / MiB / GiB / TiB aliases all use powers of 1024. Fractional values round down to whole bytes, so "1.1KB" is 1126 bytes. If this is None (default), there is no per-function byte limit, but an explicitly configured server.maxCacheDataSize budget may still evict entries. When adding a value would exceed the limit, Streamlit drops the least-recently-used entries until the new value fits. Reading a cached value makes it the most recently used. If one value alone is larger than max_size, Streamlit keeps that value, drops the other in-memory entries, and logs a warning. The next new value replaces the oversized value.  With persist="disk", only the in-memory copy is dropped. With scope="session", the limit applies to each session separately. The limit counts pickled bytes, not total process memory. |
   | 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 data 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. |
   | persist | "disk", bool, or None | None | Optional location to persist cached data to. Passing "disk" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. |
   | 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. |
   | scope | "global" or "session" |  | The scope for the data cache. If this is "global" (default), the data is cached globally. If this is "session", the data 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 cache entry 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 value is ready. "background": Return the expired value immediately and update it in the background. By default, Streamlit can keep returning the expired value for one extra ttl; after that, the next call waits for a new value. To change how long expired values can be returned, use the runner.cacheBackgroundRefreshTTLMultiplier configuration option. This mode requires a ttl and can't be used with persist. 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. |

> **Warning**
>
> `st.cache_data` implicitly uses the `pickle` module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. **Only load data you trust**.

* Function signature:

   ```python
   st.cache_data.clear()
   ```

#### Example

In the example below, pressing the "Clear All" button will clear memoized values from all functions decorated with `@st.cache_data`.

```python
import streamlit as st

@st.cache_data
def square(x):
    return x**2

@st.cache_data
def cube(x):
    return x**3

if st.button("Clear All"):
    # Clear values from *all* all in-memory and on-disk data caches:
    # i.e. clear values from both square and cube
    st.cache_data.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
@st.cache_data
def get_api_data():
    data = api.get(...)
    st.success("Fetched data from API!")  # 👈 Show a success message
    return data
```

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_data
def show_data():
    st.header("Data analysis")
    data = api.get(...)
    st.success("Fetched data from API!")
    st.write("Here is a plot of the data:")
    st.line_chart(data)
    st.write("And here is the raw data:")
    st.dataframe(data)
```
