Advance Streamlit Functions: Session State and Callback

Halis Manaz
3 min readOct 25, 2022

--

What Is Session State and Why Is It Needed?

In Streamlit, every browser tab is defined as a session and for every interaction in Streamlit, it reruns your script. That means if you define a variable for a specific value in your script, this value is defined again and again for every interaction and your variable will not be changed. But your script has to memorize the variables and change them to move forward. To solve that problem, session state variables are used. Let’s explain better with an example

Let’s create a simple script to add an A letter for every click on the “Add A” button. You will only see one letter A each time you click the button. This is because each time you click the button, the variable my_string is defined over and over as an empty string.

Streamlit application without session state variable

To deal with that problem session state variables are used.

Streamlit application with session state variable

The problem is solved. You can also use st.write(st.session_state) code to see session state variables

Widgets and Session State

You can also initialize and assign values to session state variables using widgets. The parameter you need to use for this is the key parameter. In this way

Widget and Session State Variable

You can also assign the variable you created from the slider as a value to another widget. You can also assign the value of the widget you assign a value to another session state variable. Like this

Two Widgets and Session State Variable

Callback Functions

I said at the beginning of the article that each of your interaction codes is re-executed from top to bottom. This is a situation that limits us in the vertical plane. In other words, when we press a button, we can see the result only under it. But you want to see the result of the interaction on your widget. What do you need to do? Don’t worry, that’s what callback functions are for. The only difference is that when writing the widget, you write the function name and the variables separately. It’s that simple. Let’s move on to the example.

Streamlit Application With Callback Function

Thanks For Reading, Follow Me For More

--

--

Halis Manaz

Hi, I am Halis. I am interested in Python, data analysis, and machine learning. I share what I learned, what I found interesting, and my portfolio projects