Streamlit completely resets the UI if an error occurs in an st.button on_click callback.
Is this behaviour intended?
Steps to reproduce
import streamlit as st
# Method 1): This keeps the "Hello!" and the title changed
# if st.button("Crash!"):
# Method 2): This completely resets the UI (no "Hello" and title is reset)
if __name__ == '__main__':
Run the app above with either method commented in and click the crash button.
The two methods produce the same state / look of the app after the crash.
Method 1) is the usual streamlit program flow where the page title and the widgets set up before the crash remain.
Method 2) using the on_click callback however completely resets the page title and removes all widgets created prior to the crash.
If I am understanding your question correctly, yes. A callback is something that executes as a prefix to the next page reload.
For example, if you have an st.write('Callback running...') inside your callback, you will see this line displayed at the top of the page when it finishes rerunning the page. Hence, if you encounter an error during a callback, you are at the very beginning of a page load before anything has been rendered to the page from the page’s body.
Thanks a lot for your explanation, this notion of a callback as a “prefix to the next page reload” was quite enlightening.
Would you say that the main use case of callbacks is to assign widgets new values prior to the rerun (such as st.session_state.my_multiselect = ['a', 'b', 'c']) and do any preprocessing, machine learning, etc… using the standard linear flow of streamlit instead?
Basically yes. Unless you have a fairly simple, linear logic on your page, a callback allows you to do a process before rendering so that the results of that processing are visible. If you have multiple widgets affecting each other back-and-forth, for example, you’d want to handle that with callbacks/session_state. If you just have a couple independent widgets that produce some result, you may not need a callback.