How does cache_data.clear() work?

Since my previous post did not get any reply, I will try to write a simpler one. Why does this button not clear the cache?

import streamlit as st

st.session_state

st.selectbox("Test", ["A", "B", "C"], key="test")

st.button("Clear test", on_click=st.cache_data.clear)

There is an example of using the .clear() method in the docs. You don’t use the method on the st.cache_data command itself, you use it on the function which is cached. Edit: You can use it on all cached functions or specific ones. But the “cache” is only related to decorated functions.

import streamlit as st
import time

@st.cache_data
def foo(bar):
    time.sleep(2)
    st.write(f"Executed foo({bar}).")
    return bar

st.button("Clear all cached values for `foo`", on_click=foo.clear) # use a callback

if st.button("Clear the cached value of `foo(1)`"): # use a conditional
    foo.clear(1)

foo(1)
foo(2)

Thanks for your answer! However, that is not my intended behavior, since I want to clear all the cache and not just the cache of a single function. I did read the docs and in st.cache_data - Streamlit Docs it says that I can do that with st.cache_data.clear().

At any rate, in both ways I cannot get the above mwe to work, what am I doing wrong?

My apologies. You are correct!

Your example doesn’t have any cached functions in it, but clearing the whole cache does work in this example:

import streamlit as st
import time

@st.cache_data
def foo(bar):
    time.sleep(2)
    st.write(f"Executed foo({bar}).")
    return bar

@st.cache_data
def baz(bat):
    time.sleep(2)
    st.write(f"Executed foo({bat}).")
    return bat

if st.button("Clear all cached values for `foo`"):
    foo.clear()
if st.button("Clear the cached value of `foo(1)`"):
    foo.clear(1)
if st.button("Clear the entire cache"):
    st.cache_data.clear()

foo(1)
foo(2)
baz(3)
baz(4)

Are you trying to clear Session State and reset your widgets instead?