How exactly does deleting key from st.session_state work?

We delete a key from st.session_state by saying

del st.session_state[key]

But st.session_state[key] refers to the value referred by the key.
How does this delete the key from “session_state”?

btw…
The software running this discussion forum is the best I have ever seen. Its so thoughtfully designed. The devil certainly lies in the details! Kudos for being so good at what you do! Thanks!

1 Like

What are you trying to ask? The “how” is just an implementation detail, we could look at the code but next month the implementation might change even if del keeps having the same effect, so why care?

The effect of del st.session_state[key] is that st.session_state no longer has an item with key key. That is all.

I like to think of st.session_state as just a normal python dictionary, in which case del does the same thing it does with a normal python dictionary – it removes that key (and the corresponding value) from the dictionary.

Under the hood, presumably streamlit has a method on session state called __delitem__, which is one of the special methods you can put on an object that determines what happens if you do del obj[foo]. See Python __delitem__() Magic Method – Be on the Right Side of Change

1 Like

Ah! That magic method! Thanks a lot for your technical inputs! @blackary

I always wonder how certain libraries work like Magic… as if there is an invisible meta layer somewhere.
Where can I learn all these meta features of python? Is there a nice reference you have? I found a cheatsheet here: Python Dunder Methods Cheat Sheet – Be on the Right Side of Change

Appreciate much your time! Dunder methods! Whoa!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.