Hi everyone, I recently started to use streamlit and came accross a behaviour that I don’t really understand, basically, I’m trying to create json files (so, python dicts), with as many keys/values as the user wants for each dict, the dicts are then stored in a list.
I first use a list stored in the session state to store the different key/value pairs and allow the user to add more of them, then I turn my list (and another value that’s just input once globally, so no session state there) into an actual dict, which I then store in another session state list. Here’s the code (stripped down for convenience, but the issue is still there):
import streamlit as st
if 'memoire' not in st.session_state:
st.session_state['memoire'] = []
if 'var_list' not in st.session_state:
st.session_state['var_list'] = []
variable_name = st.text_input('Variable name', value='variable_test')
variable_type = st.selectbox('Variable type', ['string', 'bool', 'float'])
variable_required = st.checkbox('Required ?')
add_to_list = st.button('Add variable')
if add_to_list:
st.session_state.var_list.append({variable_name: {"type": variable_type, "required": variable_required}})
names = []
for x in st.session_state.var_list:
for key, value in x.items():
names.append(key)
op1_name = st.selectbox('pick a variable', names)
schema = {}
for x in st.session_state.var_list:
schema.update(x)
schema[names[0]]['custom_rules'] = {}
schema[names[0]]['custom_rules']['operations'] = [{'variable': op1_name}]
display_current = st.checkbox('display current schema')
if display_current:
st.json(schema)
save_to_state = st.button("save schema to state")
if save_to_state:
st.session_state['memoire'].append(schema)
st.json(st.session_state.memoire)
I would expect that, after saving one complete dict (what I call a schema in my code), it would just stay there and that newer schemas would simply be added to the list, but that’s not the case, if you run the app and add 2 variables, say “a” and “b”, then save to state, you can see that when you change the input in the “pick a variable” field, the change also happens in “memoire” (displayed at the bottom of the app) :
let’s set the ‘pick a variable’ selectbox to ‘b’ and :
Furthermore, if you try to save several schemas, you’ll notice that they are always identical (and that changing ‘pick a variable’ edits all of them at once).
It seems to me that the ‘memoire’ variable is stored as a list of the variable ‘schema’, instead of being a list of values ‘schema’ held when it was saved, but that’s just a random guess. Is this behaviour intended in streamlit, and does anyone know of a way to get around this ?
Thanks in advance !