Hello,
It seems version 1.37 has a bug or unwanted behavior when using @st.fragment with a function that has argument(s).
See the app below:
import streamlit as st
@st.fragment
def foo(is_true:bool):
st.write(f'Enter foo: is_true = {is_true}')
if st.button('Show value'):
st.write(f'Button clicked: is_true = {is_true}')
def main():
if 'd' not in st.session_state:
d = {'is_true': False}
st.session_state.d = d
else:
d = st.session_state.d
def on_change():
st.write('Changing value ...')
d['is_true'] = not d['is_true']
st.write(f'New value: {d["is_true"]}')
st.checkbox('True?', on_change=on_change)
st.write(f'is_ture = {d["is_true"]}')
foo(d['is_true'])
if __name__ == '__main__':
main()
On reload, I see:
When clicking on the checkbox, I see:
So far, everything seems to be working correctly.
However, from this point, when clicking on the “Show value” button, it always displays a True value.
Even if is_true = False
Hello,
The fragment will keep the first data (here : True) and rerun it. This is why you got this behaviour.
“When Streamlit element commands are called directly in a fragment, the elements are cleared and redrawn on each fragment rerun, just like all elements are redrawn on each app rerun.”
The button inside the fragment always displays True regardless of the actual is_true value. This suggests that the fragment is not properly updating its state or is caching the wrong value.
Instead of passing is_true as an argument, use Session State to manage this value:
st.fragment
def foo():
st.write(f'Enter foo: is_true = {st.session_state.is_true}')
if st.button('Show value'):
st.write(f'Button clicked: is_true = {st.session_state.is_true}')
def main():
if 'is_true' not in st.session_state:
st.session_state.is_true = False
def on_change():
st.session_state.is_true = not st.session_state.is_true
st.checkbox('True?', value=st.session_state.is_true, on_change=on_change)
st.write(f'is_true = {st.session_state.is_true}')
foo()
But the first value on the first run when entering the foo function is False.
This is why I don’t really understand this behavior.
Moreover, when running the same code on version 1.36 with @st.experimental_fragment, I get a different behavior, which is also more useful and intuitive.
But how can I work with this session_state approach in case I use the function foo() with st.fragment more than once on a page?
In my case, the parameter using in the function call carries an ID. This ID decides about the content that is rendered inside the fragment (content is defined inside a database).
So I have no clue how to adapt your idea for this !?!?!?