I want to cache the instantiation of a class A and then update a property of the class in streamlit. For testing purposes, I update the property B in the app and write the new value to streamlit. However, on the next refresh of the app (selecting another number to add in the selectbox), the property B is reset to it’s initialized value 0, even though the class is not re-initialized.
Steps to reproduce
Code snippet:
import streamlit as st
from datetime import datetime
class A:
def __init__(self, instantiation_number):
self.B = instantiation_number
def update_B(self, number):
self.B += number
@st.cache_data
def instantiate_a(instantiation_number):
st.write("instantiating A at " + str(datetime.now()))
return A(instantiation_number)
A_instance = instantiate_a(0)
st.write(A_instance.B)
update_number = st.selectbox("Select a number", options=[1, 2, 3])
A_instance.update_B(update_number)
st.write(A_instance.B)
Expected behavior:
The property of the class that is updated should remain updated on the next action of the user (in this case, selecting another value to add from the selectbox)
Actual behavior:
The property B of the class is reset to 0, even though the class is not reinstantiated (see the timestamp written in the app.
The issue you’re encountering is related to how Streamlit’s caching mechanism works. By default, Streamlit will cache the function return value based on its input arguments. In your case, the instantiate_a function is decorated with @st.cache_data, which means that the return value will be cached based on the instantiation_number argument.
When the update_B method is called on the A_instance, it modifies the B property of the cached instance. However, when the app is refreshed and a new value is selected in the selectbox, the instantiate_a function is called again with a different instantiation_number. Since Streamlit detects a different input argument, it re-executes the function and returns a new instance of class A with the updated instantiation_number. Therefore, the B property is reset to its initialized value.
To solve this issue, you can modify your code as follows:
import streamlit as st
from datetime import datetime
class A:
def __init__(self, instantiation_number):
self.B = instantiation_number
def update_B(self, number):
self.B += number
@st.cache(allow_output_mutation=True)
def instantiate_a(instantiation_number):
st.write("instantiating A at " + str(datetime.now()))
return A(instantiation_number)
A_instance = instantiate_a(0)
st.write(A_instance.B)
update_number = st.selectbox("Select a number", options=[1, 2, 3])
A_instance.update_B(update_number)
st.write(A_instance.B)
In the modified code, the @st.cache decorator is used instead of @st.cache_data. The allow_output_mutation=True argument is passed to the decorator, which allows the cached object to be mutated. This way, the A_instance will retain its state even when the instantiate_a function is called again with a different instantiation_number.
I found a solution that leverages st.session_state.
What I do is the following:
if A_instance is not in the session state yet (i.e., on the first run through the script), I instantiate A_instance in line 21. As such, I instantiate it only once.
at the bottom of the script, I assign the st.session_state.A_instance with the instance of the class in line 33.
When the script is executed again, A_instance is in st.session_state and the instantiation is skipped. Instead, I assign A_instance with st.session_state.A_instance in line 23, which has my instantiated class with the value of B retained.
Here is the code:
import streamlit as st
from datetime import datetime
class A:
def __init__(self, instantiation_number):
self.B = instantiation_number
def update_B(self, number):
self.B += number
@st.cache_data
def instantiate_a(instantiation_number):
st.write("instantiating A at " + str(datetime.now()))
return A(instantiation_number)
if "A_instance" not in st.session_state:
A_instance = instantiate_a(0)
else:
A_instance = st.session_state.A_instance
st.write(A_instance.B)
update_number = st.selectbox("Select a number", options=[1, 2, 3])
A_instance.update_B(update_number)
st.write(A_instance.B)
st.session_state.A_instance = A_instance
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
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.
Performance cookies
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.
Functional cookies
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.
Targeting cookies
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.