Class property update does not get persisted when class instantiation is cached

Summary

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.

Debug info

  • Streamlit version: 1.22.0
  • Python version: 3.9.13

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.

Unfortunately, st.cache() is deprecated in the version of streamlit that I’m using (1.22.0). However, I found another solution (see below)

I found a solution that leverages st.session_state.

What I do is the following:

  1. 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.
  2. at the bottom of the script, I assign the st.session_state.A_instance with the instance of the class in line 33.
  3. 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

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.