Persistence of a single variable

Sorry for silly question, but I can’t find a simple example of how to get persistence of a single numeric variable. Could someone provide me with a code snippet? Thank you


Hi @Fabio_Pasquarella -

Does this code snippet do what you want?


Hello @randyzwitch, unfortunately it doesn’t seem to work for me. I just want to preserve a value of my computed variable along sessions, for istance:

if st.button(...):

how do I use session_state in order to preserve myvariable?
Thank you

Hello @Fabio_Pasquarella,

What error did you have when trying the code snippet @randyzwitch shared?

Alternatively to session state, you can use an experimental feature which stores variables directly in your URL, as query parameters.

Here’s a demo based on your code sample:

import streamlit as st

# Input fields
a = st.number_input("First value", 1, 1000)
b = st.number_input("Second value", 1, 1000)

# Perform an operation, and save its result
if st.button("Compute value"):
    result = a * b
    st.experimental_set_query_params(my_saved_result=result)  # Save value

# Retrieve app state
app_state = st.experimental_get_query_params()  

# Display saved result if it exist
if "my_saved_result" in app_state:
    saved_result = app_state["my_saved_result"][0]
    st.write("Here is your result", saved_result)
    st.write("No result to display, compute a value first.")

If there are parts you don’t understand, or if you don’t see how to use query params in your own code, let me know!


Hi @synode,
there wasn’t any error, it just didn’t save the values…while your code works,I just had to make some small changes. In fact I used a dictionary variable in addition to a numeric variable - maybe the code provided by @randyzwitch does not work for this reason? I noticed that app_state is a list of strings, so I just converted my dictionary to a list of keys and values in input, and back to a dictionary on output. Thank you