Error in on_click callback causes streamlit to reset the UI

Summary

Streamlit completely resets the UI if an error occurs in an st.button on_click callback.
Is this behaviour intended?

Steps to reproduce

Code snippet:

import streamlit as st

def crash():
    raise ValueError("Crashed!")

def main():
    st.set_page_config(page_title="Title")
    st.write("Hello!")
    
    # Method 1): This keeps the "Hello!" and the title changed
    # if st.button("Crash!"): 
    #    crash()
    
    # Method 2): This completely resets the UI (no "Hello" and title is reset)
    st.button("Crash!", on_click=crash)
    
if __name__ == '__main__':
    main()

Run the app above with either method commented in and click the crash button.

Expected behavior:

The two methods produce the same state / look of the app after the crash.

Actual behavior:

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.

Debug info

  • Streamlit version: 1.20.0
  • Python version: 3.8.9
  • PipEnv
  • OS version: Windows 10 Pro (21H2)
  • Browser version: Chrome 110.0.5481.178

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.

2 Likes

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.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.