Answer
As of Streamlit ≤ 1.38 there is no built‑in flag or API that automatically removes st.session_state entries created inside a @st.cache_data‑decorated function when its TTL expires.
Confirmed facts
- The
@st.cache_data decorator only caches the function’s return value; side‑effects such as assigning to st.session_state persist across reruns.
- Calling
st.cache_data.clear() or waiting for the TTL to elapse does not affect st.session_state.
Likely explanation
Streamlit treats the cached function as a pure computation; any mutation of global state (including st.session_state) is considered a side‑effect that the caching mechanism does not track, so it cannot know when to clean it up.
Recommended manual‑cleanup pattern
- Choose a distinct namespace for cache‑related keys, e.g.
_cache_ prefix.
- Inside the cached function, before setting a new value, record the key in a list stored in
st.session_state (e.g. st.session_state['_cache_keys']).
- At the start of each script run, clear any previously recorded keys before the function can set them again:
import streamlit as st
import time
@st.cache_data(ttl=5)
def get_value():
# Record keys we are about to touch
if '_cache_keys' not in st.session_state:
st.session_state['_cache_keys'] = []
key = 'cached_tmp'
st.session_state['_cache_keys'].append(key)
st.session_state[key] = time.time()
return 42
# Cleanup step – run on every rerun
for k in st.session_state.get('_cache_keys', []):
if k in st.session_state:
del st.session_state[k]
st.session_state['_cache_keys'] = [] # reset for next call
# Use the cached function
val = get_value()
st.write('Cached value:', val)
st.write('Session state keys:', list(st.session_state.keys()))
This pattern guarantees that any st.session_state entry created by the cached function is removed before the function can set it again, preventing stale data from surviving a TTL expiration.
Missing diagnostic detail
If you are using a Streamlit version newer than 1.38, please verify the release notes for any new session_state‑auto‑clear feature; the answer may change.