Towards AI Can Help your Team Adopt AI: Corporate Training, Consulting, and Talent Solutions.

Publication

Unlocking the Power of Session State in Streamlit (1/2)
Latest   Machine Learning

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.

Image by streamlit

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:

Image by the author

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:

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

Feedback ↓