Unlocking the Power of Session State in Streamlit (1/2)
Last Updated on November 5, 2023 by Editorial Team
Author(s): Stavros Theocharis
Originally published on Towards AI.
Introduction
Streamlit has had a quick surge in popularity due to its efficacy in facilitating the development of web applications with minimal exertion. Although Streamlit simplifies the process of creating interactive applications, certain projects may necessitate more intricate features. This blog article aims to examine the notion of βsession stateβ in Streamlit and illustrate its potential for developing applications that rival others in terms of functionality and user experience. There is also a second part available for you to read: Unlocking the Power of Session State in Streamlit (2/2) β Matching Rows Between Two Dataframes which includes a more practical guide.
What is a Session State?
Prior to delving into the pragmatic elements, it is imperative to establish a comprehensive understanding of the concept of session state within the Streamlit package.
As stated in the official docs:
Session State is a way to share variables between reruns, for each user session. In addition to the ability to store and persist state, Streamlit also exposes the ability to manipulate state using Callbacks. Session state also persists across apps inside a multipage app.
Why does it reference βrerunsβ?
To be as generic as I can, the answer is that each time the user interacts with something (i.e., a button), the whole code reruns. When rerunning the code, the variables included may change. In some apps, it is important to be able to keep the values of some variables between reruns and alternate them on demand. Thatβs why the session state is important. It is our storage that keeps βinformationβ between the different reruns.
How to use Session State?
So, letβs directly see some code importing the necessary libraries:
import streamlit as st
Session state can be accessed easily in order to update it, or create a new variable inside:
st.session_state.data["test_var"] = True
In the above example, a new key was added, βdataβ, including as value βtest_varβ with the value True. You can use this new variable very easily in your code, as you could with any other variable:
st.text_input("Enter your info:", session_state.data.test_var)
Leveraging Session State for Complex Functionality
The utilization of the session state is advantageous in the management of user sessions, processing form submissions, and monitoring the applicationβs state across several components. The user possesses the capability to generate conditional logic by utilizing session state variables, hence enabling the dynamic modification of the content within their application.
In this example, callbacks are being used. Letβs create a simple app that can calculate the square of a number using a callback function. Hereβs a snippet of how this can be achieved:
if "user_number" not in st.session_state:
st.session_state["user_number"] = 0
if "square_result" not in st.session_state:
st.session_state["square_result"] = 0
# Create a callback function
def calculate_square():
st.session_state["square_result"] = st.session_state.user_number**2
# Create a user input field
st.session_state.user_number = st.number_input(
"Enter a number:", value=st.session_state.user_number
)
# Add a button to trigger the calculation
button = st.button("Calculate Square", on_click=calculate_square)
st.write(
f"The square of {st.session_state.user_number} is {st.session_state.square_result}"
)
Instead of using the βon_clickβ argument, you can use something like the below (depending on your coding preference):
# Add a button to trigger the calculation
if st.button("Calculate Square")
calculate_square()
The above example app can be seen below:
Conclusion
By utilizing Streamlitβs session state feature, developers may augment the functionality and user experience of their applications to compete with more complex frameworks. By leveraging the capabilities of the session state, one can enhance the performance and functionality of Streamlit projects to a higher level. Gain firsthand experience in harnessing the potential of developing dynamic and interactive applications that have a profound influence. Embrace the opportunity and commence a venture focused on constructing outstanding applications that captivate interest and establish an enduring impact.
If you liked this article, please follow me to be notified of future ones. https://medium.com/@stavrostheocharis
The second part of the βsession stateβ series can be found here.
You can also check out my previous articles, which cover various parts of data science, AI, and software. Some of my streamlit articles are:
- Empowering Your App with Streamlitβs New Connections Feature and Interactive Plotly Maps
- How To Create an End-2-End Text Paraphrase App
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.
Published via Towards AI