Can I use st.sessions_state and a function that’s decorated with st.cache_resource ?
I couldn’t find a reference to it.
I tried using creating a function in that matter and I got errors.
Can I use st.sessions_state and a function that’s decorated with st.cache_resource ?
I couldn’t find a reference to it.
I tried using creating a function in that matter and I got errors.
Here is an example of using both st.session_state
and st.cache_resource
in the same program.
import datetime
import streamlit as st
@st.cache_resource
def answer_to_life_the_universe_and_everything():
return 42
if "date" not in st.session_state:
st.session_state.date = datetime.date.today()
answer = answer_to_life_the_universe_and_everything()
st.write(
f"The Answer to the Ultimate Question of Life, The Universe, and Everything is **{answer}**."
)
st.write(f"This session was started on **{st.session_state.date}**")
Hello @royassis,
Here’s how you can use st.session_state
with a cached function:
import streamlit as st
# Example of a cached function
@st.cache
def compute_expensive_operation(input_value):
# Simulate an expensive operation
return input_value * 2
# Initialize session state if not already done
if 'input' not in st.session_state:
st.session_state['input'] = 10
# Input widget to change the value
st.session_state['input'] = st.number_input('Input Value', value=st.session_state['input'])
# Using the cached function with a session state variable
result = compute_expensive_operation(st.session_state['input'])
st.write(f'Result: {result}')
Hope this helps!
Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer
P.S. Lets connect on LinkedIn!
➤ Want me to build your solution? Lets chat about how I can assist!
➤ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➤ Website: https://sahirmaharaj.com
➤ Email: sahir@sahirmaharaj.com
➤ 100+ FREE Power BI Themes: Download Now
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.