Save variable defined inside a button

Hello,

In a Streamlit app, I need to perform a time expensive operation, which depends on some parameters the user chooses (with sliders).

Because this operation is expensive, I want to do it only when the user click on a button to perform it (and because the operation depends on multiple parameters, the user might want to redo the operation multiple times).

Because there are multiple parameters, I also don’t really want to cache the function and recompute it every time one parameter changes. In this case, if a user wants to change 10 parameters, Streamlit will try to redo the expensive operation every time a slider changes, which will make it super slow.

A simple code to illustrate my idea is the following:

import streamlit as st

x = 0
y = None

def f(x):
    "Imagine a time expensive function here"
    y = x + 1
    return y

compute_button = st.button("Compute y")
if compute_button:
    y = f(x)

print(y)

clicked = st.button("Click me")

At the beginning, y is None.
When I click on the compute_button, y is now 1, but as soon as I click on another button (for example cliked), y goes back to None.
And I need to click other buttons after performing the expensive operation.

Do you have any idea or workaround for this?
I saw workarounds using a checkbox instead of a button, but I think it wouldn’t fit my case.
Thanks in advance

It worked super well with How to use output variables from one button in another button? - #4 by asehmi but feel free to tell me if there is a better solution