how can I clear specific streamlit cache?

Question:

I run streamlit script with a few caches.

When I use the following code it clears all the caches:

from streamlit import caching

caching.clear_cache()

I would like to clear only a specific cache. How can I do this?

Asked By: theletz

||

Answers:

This isn’t currently (easily) doable.

This is an optional solution that can be applied to some cases:

You can use the allow_output_mutation option:

import streamlit as st

@st.cache(allow_output_mutation=True)
def mutable_cache():
    return some_list

mutable_object = mutable_cache()

if st.button("Clear history cache"):
    mutable_object.clear()

I wrote the returned cached object as list but you can use other object types as well (then you have to replace the clear method which is specific to lists).

For more info please look on the answers I got in the streamlit community forum

Answered By: theletz

FYI: Streamlit is current proposing a way to clean cache on given elements (still in experimental mode though):

https://docs.streamlit.io/library/advanced-features/experimental-cache-primitives#clear-memo-and-singleton-caches-procedurally

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

if st.button("Clear Square"):
    # Clear square's memoized values:
    square.clear()

if st.button("Clear All"):
    # Clear values from *all* memoized functions:
    st.experimental_memo.clear()
Answered By: Jean-Francois T.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.