Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: [email protected]
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

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 ↓