Widget value snaps back every second time when read/write to file

I found a solution here Mini-tutorial: Initializing widget values and getting them to stick without double presses - #2 by marduk
i.e. assign the widget value stored in session state to the widget initialiser value

import streamlit as st
from yaml import load, dump, Loader, Dumper

with open('test.yaml', 'r') as f: 
    p = load(f, Loader = Loader)

for k, v in p.items():
    if k in st.session_state: v = st.session_state[k]
    p[k] = st.slider(k, 0.0, 1.0, v, key = k)

with open('test.yaml', 'w') as f: 
    dump(p, f, Dumper = Dumper)

or to avoid unnecessary reads right after writes:

import streamlit as st
from yaml import load, dump, Loader, Dumper

if not 'p' in st.session_state:
    with open('test.yaml', 'r') as f: 
      st.session_state['p'] = load(f, Loader = Loader)

for k, v in st.session_state['p'].items():
    if k in st.session_state: v = st.session_state[k]
    st.session_state['p'][k] = st.slider(k, 0.0, 1.0, v, key = k)

with open('test.yaml', 'w') as f: 
    dump(st.session_state['p'], f, Dumper = Dumper)
1 Like