Caching for initializing a variable that then is modified

Summary

It’s a short time i’ve started using streamlit, and i’m having some issues. I need to define an empty variable at the start of my script, then i need to modify that variable with some kind of recursive operations (when i press the button) and i don’t want the variable to be emptied again each time i press the button, i want to take the last value stored in the variable and modify it, without returning back to the empty variable. I built a toy example to explain better:

Steps to reproduce

Code snippet:


import streamlit as st

@st.cache(allow_output_mutation=True)
def set_init():
    return 1
# Define an empty list outside of the Streamlit app
x = set_init()

# Define the Streamlit app
st.title("My Streamlit App")

# Add a button to the app that increases x by 1 when clicked
if st.button("Add to X"):
    x=x+1

# Display the value of x on the app
st.write("X:", x)


Expected behavior:

x=1
(press the button)
x=2
(press the button)
x=3
(press the button)
x=4

Actual behavior:

x=1
(press the button)
x=2
(press the button)
x=2
(press the button)
x=2

If someone can help me, i would be glad about this!
ps. i also tried with @st.cache_data but nothing changes

I think you want session_state instead of (or in addition to) cache.

1 Like

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