The classic approach
The classic approach is quite straightforward, since it doesn’t require the with instruction:
Figure 15.7: The classic approach to introduce forms in our code
Here’s what we are doing this time:
- On line 19, we directly introduce the form.
- After that, on lines 20 and 21, we create two new widgets, text_input and selectbox, respectively.
- On line 22, we create a submit button. As usual, an if clause oversees whether or not the submit button has been pushed. It’s important to understand that, in this case, the indentation of the if clause will always be at the same level as that of the form, so the success message will always be outside the form box.
Here’s how the two forms created using the two approaches look in the browser:
Figure 15.8: Two forms created with the context manager and classic approaches
Please note that we can insert data (this means using widgets) independently into the two forms. In fact, the two submit buttons are completely unrelated.
Forms are a very powerful way of keeping widgets and components segregated in a specific area of our web app. Let’s now see how to deal with so-called sessions.
What is Session State and when do we use it?
Streamlit was launched in 2019, and statefulness was a little problem for quite a long time since states weren’t managed natively. However, starting from version 0.8.4, things changed, and the official claim (https://blog.streamlit.io/session-state-for-streamlit/) was as follows:
You can now store information across app interactions and rerun!
To be honest, that claim is really perfect because it conveys everything about sessions. Streamlit’s Session State feature offers an efficient and sophisticated approach to session management. This feature enables the storage of variables across multiple reruns, facilitates the creation of interactive events on input widgets, and allows the use of callback functions to manage these events effectively.
The robust capabilities of Session State enhance the development of various applications. These capabilities include the following:
- Integrating widgets that are interdependent
- Developing engaging stateful games, such as Battleship and Tic-Tac-Toe
- Conducting data and image annotation tasks
- Extending functionalities for diverse and complex uses, such as persistence of user data across multiple requests and efficient management of resources and data
Typically, using Streamlit without Session State means that interacting with a widget initiates a rerun, causing the variables defined in the script to reset with each execution. In contrast, employing Session State enables the preservation of variable values across reruns, which is particularly beneficial when there is a need to maintain variable states without reinitialization.